Pythonの基本的な概念の一つにif-else
文があります。これは、ある条件に基づいて異なるコードブロックを実行することを可能にします。
if-else文の基本的な構文
if condition:
# do something if condition is True
else:
# do something else if condition is False
ここで、condition
はTrueまたはFalseに評価される任意の式です。例えば、比較演算子(==
, !=
, <
, >
, <=
, >=
)や論理演算子(and
, or
, not
)を使用して条件を作成することができます。
Pythonのif-else文を使った演習
以下に、Pythonのif-else文を使った初心者向けの演習をいくつか紹介します。
演習1: 偶数または奇数のチェック
num = int(input("Enter an integer: "))
if num % 2 == 0:
print(num, "is even.")
else:
print(num, "is odd.")
このプログラムは、入力された整数が偶数か奇数かを判定します。
演習2: 成績計算器
score = float(input("Enter your score: "))
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("F")
このプログラムは、学生のスコアに基づいて成績を計算し表示します。
演習3: 閏年チェッカー
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
このプログラムは、指定された年が閏年かどうかをチェックします。
これらの演習を通じて、Pythonのif-else文の使い方を理解し、スキルを磨くことができます。