ななぶろ

-お役立ち情報を気楽に紹介するブログ-

Pythonプログラム練習問題10選:JupyterNotebookを活用した学習ガイド

www.amazon.co.jp

Pythonプログラム練習問題10選:Jupyter Notebookを活用した学習ガイド

Pythonは、その汎用性と豊富なライブラリによって、データサイエンス、機械学習、Web開発など幅広い分野で利用される人気のプログラミング言語です。しかし、Pythonを習得するには、実際にコードを書き、問題を解決する練習が不可欠です。

本記事では、Jupyter Notebookを活用しながら取り組めるPythonプログラムの練習問題10選を紹介します。初心者から中級者まで対応できるよう、難易度も様々にご用意しました。各問題には、解答例と解説を記載しており、学習の進捗に合わせてステップアップできます。

1. Jupyter Notebookとは?

まず、Jupyter Notebookについて簡単に説明します。Jupyter Notebookは、コード、テキスト(Markdown)、数式、画像などをまとめて記述・実行できるインタラクティブな環境です。Webブラウザ上で動作し、コードをセル単位で実行できるため、試行錯誤しながら学習を進めるのに最適です。

Jupyter Notebookのメリット:

  • 可視化しやすい: コードと結果が同じ場所に表示されるため、理解しやすい
  • インタラクティブな実行: セルごとにコードを実行できるため、デバッグや実験が容易
  • ドキュメント作成に便利: Markdownでテキストを記述できるため、レポートやプレゼンテーション資料の作成にも活用可能
  • 共有が簡単: Notebookファイルを共有することで、他の人と共同作業しやすい

Jupyter Notebookのインストール:

Jupyter Notebookは、AnacondaというPythonディストリビューションに含まれているので、AnacondaをインストールすればJupyter Notebookも一緒にインストールされます。Anacondaは、データサイエンスに必要な様々なライブラリやツールをまとめて提供する便利なパッケージです。

Anaconda公式サイト

Anacondaのインストール手順は以下の通りです。

  1. Anacondaのウェブサイトからインストーラをダウンロードします。
  2. インストーラを実行し、指示に従ってインストールを進めます。
  3. インストール中に、Jupyter Notebookを起動するかどうか尋ねられますが、「Yes」を選択するとインストール完了後に自動的に起動されます。

または、pipを使って個別にインストールすることも可能です。pipはPythonのパッケージ管理システムで、コマンドラインから様々なライブラリを簡単にインストールできます。

pip install jupyter

Jupyter Notebookの起動:

ターミナル(Windowsの場合はコマンドプロンプト)で以下のコマンドを実行します。

jupyter notebook

Webブラウザが自動的に開き、Notebookファイルを選択できます。新しいNotebookを作成するには、「New」ボタンをクリックし、「Python 3」を選択します。

英文説明:

Jupyter Notebook is an interactive computing environment that allows you to create and share documents containing live code, equations, visualizations, and narrative text. It's a web-based application that runs in your browser and lets you execute code cells individually, making it ideal for experimentation and learning.

Benefits of Jupyter Notebook:

  • Visualization: Code and results are displayed together, enhancing understanding.
  • Interactive Execution: Cells can be executed independently, facilitating debugging and experimentation.
  • Documentation: Markdown support allows for creating reports and presentations.
  • Sharing: Notebook files can be easily shared with others for collaboration.

Installation:

Jupyter Notebook is included in Anaconda, a Python distribution that provides many data science libraries and tools. You can download Anaconda from Anaconda website. Follow the installation instructions provided on the website. Alternatively, you can install Jupyter Notebook separately using pip: pip install jupyter.

Launching:

Open your terminal (or command prompt) and run the following command: jupyter notebook. This will open a web browser with the Jupyter Notebook interface. Click "New" and select "Python 3" to create a new notebook.

2. 練習問題1:FizzBuzz問題

問題: 1からNまでの整数を順番に出力するプログラムを作成してください。ただし、3の倍数の場合は "Fizz"、5の倍数の場合は "Buzz"、3と5両方の倍数の場合は "FizzBuzz" と出力します。

解答例:

def fizzbuzz(n):
  """1からnまでの整数を出力し、3の倍数ならFizz, 5の倍数ならBuzz, 両方ならFizzBuzzと出力する関数"""
  for i in range(1, n + 1):
    if i % 3 == 0 and i % 5 == 0:
      print("FizzBuzz")
    elif i % 3 == 0:
      print("Fizz")
    elif i % 5 == 0:
      print("Buzz")
    else:
      print(i)

# 例:1から15までの整数に対してFizzBuzzを実行
fizzbuzz(15)

解説:

  • def fizzbuzz(n): は、引数として整数 n を受け取る関数を定義します。
  • for i in range(1, n + 1): は、1から n までの整数のシーケンスを生成し、各整数 i に対してループ処理を行います。 range(1, n + 1) は、1から始まり n まで(n を含まない)の数列を生成します。
  • if i % 3 == 0 and i % 5 == 0: は、変数 i が3と5の両方の倍数であるかどうかを判定します。 % は剰余演算子で、割り算の余りを返します。したがって、i % 3 == 0i が3で割り切れる(つまり、3の倍数)かどうかをチェックし、i % 5 == 0i が5で割り切れる(つまり、5の倍数)かどうかをチェックします。 and 演算子を使用すると、両方の条件が真である場合にのみ、if ブロック内のコードが実行されます。
  • print("FizzBuzz") は、i が3と5の両方の倍数の場合(つまり、15の倍数)に "FizzBuzz" を出力します。
  • elif i % 3 == 0: は、i が3の倍数であるかどうかを判定します。 elif は「そうでなければ、もし」という意味で、前の if 条件が偽であった場合にのみ評価されます。
  • print("Fizz") は、i が3の倍数の場合(ただし、5の倍数ではない)に "Fizz" を出力します。
  • elif i % 5 == 0: は、i が5の倍数であるかどうかを判定します。
  • print("Buzz") は、i が5の倍数の場合(ただし、3の倍数ではない)に "Buzz" を出力します。
  • else: は、上記のどの条件も真でない場合に実行されます。つまり、i が3でも5でもない場合です。
  • print(i) は、i が3でも5でもない場合に i の値をそのまま出力します。

英文説明:

Problem: Write a program that prints numbers from 1 to N. For multiples of 3, print "Fizz". For multiples of 5, print "Buzz". For multiples of both 3 and 5, print "FizzBuzz".

Solution:

def fizzbuzz(n):
  """Prints numbers from 1 to n, replacing multiples of 3 with "Fizz", 5 with "Buzz", and both with "FizzBuzz"."""
  for i in range(1, n + 1):
    if i % 3 == 0 and i % 5 == 0:
      print("FizzBuzz")
    elif i % 3 == 0:
      print("Fizz")
    elif i % 5 == 0:
      print("Buzz")
    else:
      print(i)

# Example: Execute FizzBuzz for numbers from 1 to 15
fizzbuzz(15)

Explanation:

  • The def fizzbuzz(n): line defines a function named fizzbuzz that takes an integer n as input.
  • The for i in range(1, n + 1): loop iterates through numbers from 1 to n. range(1, n + 1) generates a sequence of numbers starting from 1 and ending at n.
  • if i % 3 == 0 and i % 5 == 0: checks if the number i is divisible by both 3 and 5. The % operator returns the remainder of a division. If the remainder is 0, it means the number is divisible. The and operator ensures that both conditions must be true for the code inside the if block to execute.
  • print("FizzBuzz") prints "FizzBuzz" if i is divisible by both 3 and 5 (e.g., 15).
  • elif i % 3 == 0: checks if i is divisible by 3, but only if it's not already divisible by both 3 and 5 (because the previous if condition would have been true in that case).
  • print("Fizz") prints "Fizz" if i is divisible by 3.
  • elif i % 5 == 0: checks if i is divisible by 5, but only if it's not already divisible by 3 or both 3 and 5.
  • print("Buzz") prints "Buzz" if i is divisible by 5.
  • else: executes if none of the previous conditions are true (i.e., i is not divisible by either 3 or 5).
  • print(i) prints the value of i itself.

3. 練習問題2:素数判定

問題: 与えられた整数が素数であるかどうかを判定する関数を作成してください。

解答例:

def is_prime(n):
  """与えられた整数が素数かどうかを判定する関数"""
  if n <= 1:
    return False
  for i in range(2, int(n**0.5) + 1):
    if n % i == 0:
      return False
  return True

# 例:1から20までの整数に対して素数判定を実行
for i in range(1, 21):
  if is_prime(i):
    print(i)

解説:

  • def is_prime(n): は、引数として整数 n を受け取る関数を定義します。
  • if n <= 1: は、入力された数値が1以下の場合、素数ではないため False を返します。 素数は2以上の自然数である必要があります。
  • for i in range(2, int(n**0.5) + 1): は、2から n の平方根までの整数のシーケンスを生成し、各整数 i に対してループ処理を行います。 n**0.5n の平方根を計算します。 int() 関数は、浮動小数点数を最も近い整数に変換します。 + 1 を加えることで、平方根が整数の場合も確実にチェックされます。 素数判定では、2からその数値の平方根までの範囲で割り切れるかどうかを確認するだけで十分です。
  • if n % i == 0: は、変数 ni で割り切れるかどうかを判定します。 もし割り切れる場合、n は素数ではないため、関数は False を返します。
  • return True は、上記のループが完了し、n が2からその平方根までのどの整数でも割り切れない場合に実行されます。 これは、n が素数であることを意味するため、関数は True を返します。

英文説明:

Problem: Write a function that determines whether a given integer is prime.

Solution:

def is_prime(n):
  """Determines if a given integer is prime."""
  if n <= 1:
    return False
  for i in range(2, int(n**0.5) + 1):
    if n % i == 0:
      return False
  return True

# Example: Check for primality of numbers from 1 to 20
for i in range(1, 21):
  if is_prime(i):
    print(i)

Explanation:

  • def is_prime(n): defines a function named is_prime that takes an integer n as input.
  • if n <= 1: checks if the number is less than or equal to 1. If it is, it's not prime and returns False. Prime numbers are greater than 1.
  • for i in range(2, int(n**0.5) + 1): iterates from 2 up to the square root of n. We only need to check divisibility up to the square root because if a number has a divisor larger than its square root, it must also have a divisor smaller than its square root.
  • if n % i == 0: checks if n is divisible by i. If it is, then n is not prime and returns False.
  • return True is executed if the loop completes without finding any divisors. This means that n is prime and returns True.

4. 練習問題3:フィボナッチ数列

問題: n番目のフィボナッチ数を計算する関数を作成してください。

解答例:

def fibonacci(n):
  """n番目のフィボナッチ数を計算する関数"""
  if n <= 1:
    return n
  else:
    return fibonacci(n-1) + fibonacci(n-2)

# 例:1から10までのフィボナッチ数列を表示
for i in range(1, 11):
  print(fibonacci(i))

解説:

  • def fibonacci(n): は、引数として整数 n を受け取る関数を定義します。
  • if n <= 1: は、入力された数値が1以下の場合、フィボナッチ数列の最初の2つの数はそれぞれ0と1であるため、n の値をそのまま返します。
  • else: は、入力された数値が2以上の場合に実行されます。
  • return fibonacci(n-1) + fibonacci(n-2) は、再帰的にフィボナッチ数列を計算します。 n番目のフィボナッチ数は、(n-1)番目と(n-2)番目のフィボナッチ数の和として定義されます。 この関数は自身を呼び出すことで、より小さいフィボナッチ数を計算し、それらを合計して結果を返します。

英文説明:

Problem: Write a function to calculate the nth Fibonacci number.

Solution:

def fibonacci(n):
  """Calculates the nth Fibonacci number."""
  if n <= 1:
    return n
  else:
    return fibonacci(n-1) + fibonacci(n-2)

# Example: Print the first 10 Fibonacci numbers
for i in range(1, 11):
  print(fibonacci(i))

Explanation:

  • def fibonacci(n): defines a function named fibonacci that takes an integer n as input.
  • if n <= 1: checks if n is less than or equal to 1. If it is, the function returns n. The first two Fibonacci numbers are F(0) = 0 and F(1) = 1.
  • else: executes when n is greater than 1.
  • return fibonacci(n-1) + fibonacci(n-2) recursively calculates the nth Fibonacci number by summing the (n-1)th and (n-2)th Fibonacci numbers. This continues until it reaches the base cases of n=0 or n=1.

5. 練習問題4:リストの合計

問題: リスト内の数値の合計を計算する関数を作成してください。

解答例:

def sum_list(numbers):
  """リスト内の数値の合計を計算する関数"""
  total = 0
  for number in numbers:
    total += number
  return total

# 例:リスト[1, 2, 3, 4, 5]の合計を計算
numbers = [1, 2, 3, 4, 5]
print(sum_list(numbers))

解説:

  • def sum_list(numbers): は、引数として数値のリスト numbers を受け取る関数を定義します。
  • total = 0 は、合計値を格納するための変数 total を初期化します。 この変数は最初は0に設定されます。
  • for number in numbers: は、リスト内の各数値を順番に処理するループです。 number 変数は、リストの現在の要素を表します。
  • total += number は、現在の数値 number を変数 total に加算します。 これは、total = total + number と同じ意味です。
  • return total は、ループが完了した後、計算された合計値 total を返します。

英文説明:

Problem: Write a function to calculate the sum of numbers in a list.

Solution:

def sum_list(numbers):
  """Calculates the sum of numbers in a list."""
  total = 0
  for number in numbers:
    total += number
  return total

# Example: Calculate the sum of the list [1, 2, 3, 4, 5]
numbers = [1, 2, 3, 4, 5]
print(sum_list(numbers))

Explanation:

  • def sum_list(numbers): defines a function named sum_list that takes a list of numbers as input.
  • total = 0 initializes a variable called total to store the sum. It starts at zero.
  • for number in numbers: iterates through each number in the input list.
  • total += number adds the current number to the running total. This is shorthand for total = total + number.
  • return total returns the final calculated sum.

6. 練習問題5:文字列反転

問題: 与えられた文字列を反転する関数を作成してください。

解答例:

def reverse_string(s):
  """与えられた文字列を反転する関数"""
  return s[::-1]

# 例:文字列"hello"を反転
s = "hello"
print(reverse_string(s))

解説:

  • def reverse_string(s): は、引数として文字列 s を受け取る関数を定義します。
  • return s[::-1] は、Pythonのスライス機能を使って文字列を反転します。 [::-1] は、文字列全体を選択し、逆方向に1ステップずつ進むことを意味します。 これにより、元の文字列の文字が逆順に並べられた新しい文字列が作成されます。

英文説明:

Problem: Write a function to reverse a given string.

Solution:

def reverse_string(s):
  """Reverses a given string."""
  return s[::-1]

# Example: Reverse the string "hello"
s = "hello"
print(reverse_string(s))

Explanation:

  • def reverse_string(s): defines a function named reverse_string that takes a string s as input.
  • return s[::-1] uses Python's slicing feature to efficiently reverse the string. The slice [::-1] creates a reversed copy of the string without modifying the original.

7. 練習問題6:単語のカウント

問題: 文字列内の各単語の出現回数をカウントする関数を作成してください。

解答例:

def count_words(text):
  """文字列内の各単語の出現回数をカウントする関数"""
  words = text.lower().split()
  word_counts = {}
  for word in words:
    if word in word_counts:
      word_counts[word] += 1
    else:
      word_counts[word] = 1
  return word_counts

# 例:文字列"This is a test string. This is another test."内の単語の出現回数をカウント
text = "This is a test string. This is another test."
print(count_words(text))

解説:

  • def count_words(text): は、引数として文字列 text を受け取る関数を定義します。
  • words = text.lower().split() は、文字列を小文字に変換し、空白で分割して単語のリストを作成します。 .lower() メソッドはすべての文字を小文字に変換し、.split() メソッドは文字列を空白で区切って単語のリストにします。
  • word_counts = {} は、単語とその出現回数を格納する辞書を初期化します。 この辞書は最初は空です。
  • for word in words: は、単語のリスト内の各単語を順番に処理するループです。
  • if word in word_counts: は、現在の単語がすでに word_counts 辞書のキーとして存在するかどうかを確認します。 もし存在すれば、その単語の出現回数を1増やします。
  • else: は、現在の単語がまだ word_counts 辞書に存在しない場合(つまり、初めてこの単語に出会った場合)に実行されます。 この場合、新しいキーとして単語を追加し、その出現回数を1に設定します。
  • return word_counts は、計算された単語の出現回数を含む辞書を返します。

英文説明:

Problem: Write a function to count the occurrences of each word in a string.

Solution:

def count_words(text):
  """Counts the occurrences of each word in a string."""
  words = text.lower().split()
  word_counts = {}
  for word in words:
    if word in word_counts:
      word_counts[word] += 1
    else:
      word_counts[word] = 1
  return word_counts

# Example: Count the occurrences of each word in the string "This is a test string. This is another test."
text = "This is a test string. This is another test."
print(count_words(text))

Explanation:

  • def count_words(text): defines a function named count_words that takes a string text as input.
  • words = text.lower().split() converts the input string to lowercase and splits it into a list of words using whitespace as the delimiter.
  • word_counts = {} initializes an empty dictionary called word_counts. This dictionary will store each word as a key and its count as the value.
  • for word in words: iterates through each word in the words list.
  • if word in word_counts: checks if the current word is already a key in the word_counts dictionary. If it is, it means we've encountered this word before, so we increment its count by 1.
  • else: If the word is not yet in the word_counts dictionary, it means this is the first time we're seeing this word. We add the word as a new key to the dictionary and set its initial count to 1.
  • return word_counts returns the word_counts dictionary containing each word and its corresponding occurrence count.

8. 練習問題7:リストのソート

問題: 与えられたリストを昇順にソートする関数を作成してください。

解答例:

def sort_list(numbers):
  """与えられたリストを昇順にソートする関数"""
  numbers.sort()
  return numbers

# 例:リスト[5, 2, 8, 1, 9]をソート
numbers = [5, 2, 8, 1, 9]
print(sort_list(numbers))

解説:

  • def sort_list(numbers): は、引数として数値のリスト numbers を受け取る関数を定義します。
  • numbers.sort() は、Pythonの組み込みメソッドを使用してリストをその場で昇順にソートします。 このメソッドは元のリストを変更し、新しいソートされたリストを作成しません。
  • return numbers は、ソートされたリストを返します。

英文説明:

Problem: Write a function to sort a given list in ascending order.

Solution:

def sort_list(numbers):
  """Sorts a given list in ascending order."""
  numbers.sort()
  return numbers

# Example: Sort the list [5, 2, 8, 1, 9]
numbers = [5, 2, 8, 1, 9]
print(sort_list(numbers))

Explanation:

  • def sort_list(numbers): defines a function named sort_list that takes a list of numbers as input.
  • numbers.sort() uses Python's built-in sort() method to sort the list in ascending order in place. This means the original list is modified directly, and no new sorted list is created.
  • return numbers returns the now-sorted list.

9. 練習問題8:ファイル読み込み

問題: テキストファイルを読み込み、各行を出力するプログラムを作成してください。

解答例:

def read_file(filename):
  """テキストファイルを読み込み、各行を出力する関数"""
  try:
    with open(filename, 'r') as f:
      for line in f:
        print(line.strip()) # 改行文字を削除して出力
  except FileNotFoundError:
    print(f"ファイル {filename} が見つかりません。")

# 例:'my_file.txt'というファイルを読み込み、各行を出力
read_file('my_file.txt')

解説:

  • def read_file(filename): は、引数としてファイル名 filename を受け取る関数を定義します。
  • try...except FileNotFoundError: ブロックは、ファイルが存在しない場合に発生する可能性のあるエラーを処理するために使用されます。
  • with open(filename, 'r') as f: は、指定されたファイルを開き、読み取りモード ('r') でファイルオブジェクト f を作成します。 with ステートメントを使用すると、ブロックの終了時にファイルが自動的に閉じられるため、リソース管理が容易になります。
  • for line in f: は、ファイル内の各行を順番に処理するループです。
  • print(line.strip()) は、現在の行を出力します。 .strip() メソッドは、文字列の先頭と末尾にある空白文字(改行文字を含む)を削除し、出力がよりクリーンになるようにします。
  • except FileNotFoundError: ブロックは、指定されたファイルが見つからない場合に実行されます。 この場合、エラーメッセージが出力され、プログラムは続行しません。

英文説明:

Problem: Write a program to read a text file and print each line.

Solution:

def read_file(filename):
  """Reads a text file and prints each line."""
  try:
    with open(filename, 'r') as f:
      for line in f:
        print(line.strip()) # Remove newline characters before printing
  except FileNotFoundError:
    print(f"File {filename} not found.")

# Example: Read and print each line of the file 'my_file.txt'
read_file('my_file.txt')

Explanation:

  • def read_file(filename): defines a function named read_file that takes the filename as input.
  • The try...except FileNotFoundError: block handles potential errors if the specified file does not exist.
  • with open(filename, 'r') as f: opens the file in read mode ('r') and assigns the file object to the variable f. The with statement ensures that the file is automatically closed when the block finishes executing, even if errors occur.
  • for line in f: iterates through each line of the file.
  • print(line.strip()) prints each line after removing any leading or trailing whitespace (including newline characters) using the strip() method. This makes the output cleaner.
  • The except FileNotFoundError: block is executed if the specified file cannot be found, printing an error message to the console.

10. 練習問題9:Webスクレイピング (BeautifulSoup)

問題: 特定のウェブサイトからタイトルを取得するプログラムを作成してください。(例: https://www.example.com/)

解答例:

import requests
from bs4 import BeautifulSoup

def get_website_title(url):
    """指定されたURLのウェブサイトのタイトルを取得する関数"""
    try:
        response = requests.get(url)
        response.raise_for_status()  # HTTPエラーが発生した場合に例外を発生させる

        soup = BeautifulSoup(response.content, 'html.parser')
        title = soup.title.string
        return title
    except requests.exceptions.RequestException as e:
        print(f"リクエストエラー: {e}")
        return None
    except AttributeError:
        print("タイトルが見つかりませんでした。")
        return None

# 例:https://www.example.comのタイトルを取得
url = "https://www.example.com/"
title = get_website_title(url)
if title:
    print(f"ウェブサイトのタイトル: {title}")

解説:

  • import requests: HTTPリクエストを送信するためのライブラリ requests をインポートします。このライブラリは、Webページを取得するために使用されます。
  • from bs4 import BeautifulSoup: HTML/XMLドキュメントを解析するためのライブラリ BeautifulSoup をインポートします。このライブラリは、取得したHTMLコンテンツから必要な情報を抽出するために使用されます。
  • def get_website_title(url): は、引数としてURLを受け取る関数を定義します。
  • try...except ブロックは、エラー処理のために使用されます。 特に、HTTPリクエストのエラー(例:サーバーがダウンしている)や、HTMLドキュメントに<title>タグが存在しない場合のエラーを処理します。
  • response = requests.get(url): 指定されたURLにGETリクエストを送信し、レスポンスオブジェクトを取得します。 このレスポンスオブジェクトには、Webページの内容が含まれています。
  • response.raise_for_status(): レスポンスのステータスコードがエラーを示す場合(4xxまたは5xx)、例外を発生させます。これにより、リクエストが成功したかどうかを確認できます。
  • soup = BeautifulSoup(response.content, 'html.parser'): レスポンスの内容をBeautifulSoupオブジェクトに解析します。 'html.parser' はHTMLパーサーを指定します。 BeautifulSoupは、HTML/XMLドキュメントをツリー構造として表現し、特定の要素を簡単に検索できるようにします。
  • title = soup.title.string: BeautifulSoupオブジェクトから<title>タグの文字列を取得します。 .title<title>タグを表し、.string はそのタグの内容(つまりウェブページのタイトル)を表します。
  • except requests.exceptions.RequestException as e:: リクエスト中にエラーが発生した場合(例:接続エラー、タイムアウト)に例外を処理します。
  • except AttributeError:: タイトルが見つからない場合に例外を処理します。
  • if title: は、タイトルが正常に取得できたかどうかを確認します。 取得できた場合は、タイトルを出力します。

英文説明:

Problem: Write a program to extract the title from a specific website (e.g., https://www.example.com/).

Solution:

import requests
from bs4 import BeautifulSoup

def get_website_title(url):
    """Extracts the title of a website given its URL."""
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for bad status codes (4xx or 5xx)

        soup = BeautifulSoup(response.content, 'html.parser')
        title = soup.title.string
        return title
    except requests.exceptions.RequestException as e:
        print(f"Request error: {e}")
        return None
    except AttributeError:
        print("Title not found.")
        return None

# Example: Get the title of https://www.example.com/
url = "https://www.example.com/"
title = get_website_title(url)
if title:
    print(f"Website title: {title}")

Explanation:

  • import requests: Imports the requests library, which is used to send HTTP requests to retrieve web pages.
  • from bs4 import BeautifulSoup: Imports the BeautifulSoup library, which is used to parse HTML/XML documents and extract data from them.
  • def get_website_title(url): defines a function named get_website_title that takes the URL of the website as input.
  • The try...except block handles potential errors during the process, such as HTTP request errors or cases where the <title> tag is missing from the HTML document.
  • response = requests.get(url): Sends a GET request to the specified URL and retrieves the response object, which contains the content of the web page.
  • response.raise_for_status(): Checks if the HTTP status code in the response indicates an error (4xx or 5xx). If it does, an exception is raised.
  • soup = BeautifulSoup(response.content, 'html.parser'): Parses the content of the response using BeautifulSoup, creating a BeautifulSoup object that represents the HTML structure as a tree. 'html.parser' specifies the HTML parser to use.
  • title = soup.title.string: Extracts the text content of the <title> tag from the BeautifulSoup object. .title refers to the <title> tag, and .string retrieves its textual content (the website title).
  • except requests.exceptions.RequestException as e:: Catches exceptions that occur during the HTTP request process, such as connection errors or timeouts.
  • except AttributeError:: Catches exceptions that occur if the <title> tag is not found in the HTML document. *