Pythonの構文

Pythonの構文

この記事ではPythonの構文について説明します。

YouTube Video

Pythonにおける構文

インデント

Pythonはインデント(字下げ)によってブロックを定義します。他の多くの言語が波括弧 {} を使用してコードブロックを定義するのに対し、Pythonはインデントを使います。通常、スペース4つでインデントをしますが、タブを使うこともできます。ただし、一つのファイル内でスペースとタブを混用しないように注意が必要です。

1x = 5
2if x > 0:
3    print("Positive")
4else:
5    print("Non-positive")

コメント

単一行コメント

Pythonではコメントは # で始まります。行末までがコメントとして扱われます。

1# This is a comment
2print("Hello, World!")  # This is also a comment

ドキュメンテーション文字列 (Docstring)

Docstringは、コードの説明を記述するために使われる文字列で、3つのダブルクォーテーション"""または3つのシングルクォーテーション'''で囲みます。主に、モジュール、クラス、関数の説明に使用されます。

1def greet(name):
2    """
3    This function displays a greeting to the specified name.
4
5    Parameters:
6        name (str): The name of the person to greet.
7    """
8    print(f"Hello, {name}!")

Docstringは、help()関数で表示できます。

1help(greet)

コメントのベストプラクティス

コメントのベストプラクティスとして次の点があります。

 1# Good example
 2# Validate user input and display a personalized message
 3
 4# Ask for the user's name
 5name = input("Enter your name: ")
 6
 7# Ask for the user's age and convert it to an integer
 8age = int(input("Enter your age: "))
 9
10# Check eligibility based on age
11if age >= 18:
12    # Inform the user that they can register
13    print(f"Welcome, {name}! You are eligible to register.")
14else:
15    # Inform the user that they are underage
16    print(f"Sorry, {name}. You must be at least 18 years old to register.")
17
18# Bad example
19# Store the user's name in the variable 'name'
20name = input("Enter your name: ")
21
22# Convert the input to an integer and store it in 'age'
23age = int(input("Enter your age: "))
24
25# Check if the user is greater than or equal to 18
26if age >= 18:
27    # Print a welcome message
28    print(f"Welcome, {name}! You are eligible to register.")
29else:
30    # Print a rejection message
31    print(f"Sorry, {name}. You must be at least 18 years old to register.")
  • 明確で簡潔に コメントはコードの意図を分かりやすく説明するために使います。

  • コードの意味を繰り返さない 自明なコードにはコメントを付けないようにします。

  • 一貫性を保つ チームでの開発では、コメントのスタイルやフォーマットを統一することが重要です。

変数とデータ型

Pythonでは変数の宣言時に型を指定する必要はありません。代入時に自動的に型が決まります。

1x = 10        # Integer
2y = 3.14      # Floating-point number
3name = "Alice"  # String (text)
4is_active = True  # Boolean value (True or False)

条件分岐

条件分岐には ifelif(else if)、else を使います。

1x = 0
2if x > 0:
3    print("Positive")
4elif x == 0:
5    print("Zero")
6else:
7    print("Negative")

ループ

Pythonでは for 文と while 文があり、異なる方法で使用されます。

for

for文は、通常リストやタプルの要素をイテレートするのに使われます。

1fruits = ["apple", "banana", "cherry"]
2for fruit in fruits:
3    print(fruit)

while

while文は、条件が真である限りループを繰り返します。

1count = 0
2while count < 5:
3    print(count)
4    count += 1

関数の定義

Pythonでは def キーワードを使って関数を定義します。

1def greet(name):
2    print(f"Hello, {name}!")
3
4greet("Alice")

クラスの定義

Pythonでは class キーワードを使ってクラスを定義し、オブジェクト指向のプログラミングができます。

1class Dog:
2    def __init__(self, name):
3        self.name = name
4
5    def bark(self):
6        print("Woof!")
7
8dog = Dog("Fido")
9dog.bark()

モジュールとインポート

Pythonでは、importキーワードを使用してモジュールをインポートし、既存のコードにアクセスできます。

1# Importing the sqrt function from the math module
2from math import sqrt
3
4result = sqrt(16)
5print(result)  # Output: 4.0

エラーと例外処理

Pythonのtry-except構造は、エラーや予期しない状況を処理します。

1# Catching a division-by-zero error example
2try:
3    result = 10 / 0
4except ZeroDivisionError:
5    print("Cannot divide by zero.")

結論

Pythonの基本的な構文は非常にシンプルで可読性が高いです。これらの基本は、Pythonのコードを書くために欠かせない要素です。

YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。

YouTube Video