Pythonの条件分岐とネスト構造
Pythonでは、if、if-else、if-elif-elseの条件分岐構文が利用可能であり、これらをネストすることで複雑な条件判断を実現できます。
条件分岐のネスト例
score = int(input("点数を入力してください:"))
if score >= 80:
print("評価:優")
elif score >= 60:
if score >= 70:
print("評価:良")
else:
print("評価:可")
else:
print("評価:不可")
Pythonの空文:passの使い方
コード構造を先に定義しておきながら、後で実装を追加する際に役立つのがpass文です。
age = int(input("年齢を入力してください:"))
if age < 12:
print("幼児")
elif 12 <= age < 18:
print("青少年")
elif 18 <= age < 30:
pass # 今後の実装予定
else:
print("成人")
アサーションの活用
デバッグ時に便利なのがassert文。条件が偽の場合にAssertionErrorを発生させます。
def calc_discount(price, discount_rate):
discounted_price = price * (1 - discount_rate)
assert 0 <= discounted_price <= price, "割引価格が無効です"
return discounted_price
print(calc_discount(1000, 0.2)) # 正常なケース
print(calc_discount(1000, 1.5)) # エラーになるケース
whileループの基本と応用
条件が成立している間、処理を繰り返すwhileループ。
count = 1
while count <= 10:
print(f"カウント:{count}")
count += 1
print("ループ終了")
whileループの注意点
- 無限ループを防ぐためには、必ず条件が偽になるケースを用意する
- インデントは4スペースが推奨
forループの基本と応用
シーケンス型の要素を順番に処理するforループ。
chars = "Pythonプログラミング"
for char in chars:
print(char, end="")
print()
数値範囲の処理
total = 0
for num in range(1, 101):
total += num
print(f"1から100までの合計:{total}")
辞書の処理
website = {
"Python": "https://example.com/python",
"Java": "https://example.com/java",
"JavaScript": "https://example.com/js"
}
for key, value in website.items():
print(f"{key}のURL:{value}")
ループのネスト
ループ構造の入れ子も可能です。
for i in range(1, 10):
for j in range(1, 10):
print(f"{i*j:3}", end="")
print()
ループ制御:breakとcontinue
breakの使い方
chars = "Python,Java,C++,JavaScript"
for char in chars:
if char == ",":
break
print(char, end="")
print("\nループを中断しました")
continueの使い方
chars = "Python,Java,C++,JavaScript"
for char in chars:
if char == ",":
print()
continue
print(char, end="")
無限ループの回避方法
以下のようなコードは無限ループになるため注意が必要です。
i = 1
while i <= 5:
print(i)
修正版:
i = 1
while i <= 5:
print(i)
i += 1
リスト内包表記
簡潔にリストを生成する機能。
# 0〜9の平方を格納したリスト
squares = [x*x for x in range(10)]
print(squares)
# 偶数のみの平方を生成
even_squares = [x*x for x in range(10) if x % 2 == 0]
print(even_squares)
辞書内包表記
fruits = ["apple", "banana", "cherry"]
fruit_lengths = {fruit: len(fruit) for fruit in fruits}
print(fruit_lengths)