0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの便利技と注意点:条件編

Last updated at Posted at 2022-08-29

目次に戻る

範囲条件を簡単に

数字 < 変数 < 数字
>>> num = int(input())
5
>>> if 1 < num < 10:
	print(num)

5
数字 <= 変数 <= 数字
>>> num = int(input())
3
>>> if 1 <= num <= 5:
	print(num)
	
3

分岐が複数でmatch-caseを使わずに条件分岐させる技

辞書を活用することで、長い分岐をスッキリさせることが可能。

if文を使う場合
born_month = int(input("生まれた月を入力してください。旧暦の月名に変換します。(1-12)"))
if born_month == 1:
    print("睦月")
elif born_month == 2:
    print("如月")
elif born_month == 3:
    print("弥生")
elif born_month == 4:
    print("卯月")
elif born_month == 5:
    print("皐月")
elif born_month == 6:
    print("水無月")
elif born_month == 7:
    print("文月")
elif born_month == 8:
    print("葉月")
elif born_month == 9:
    print("長月")
elif born_month == 10:
    print("神無月")
elif born_month == 11:
    print("霜月")
elif born_month == 12:
    print("師走")
else:
    print("1 から 12までの数字を半角英数で入力してください")
if文を使わない技
old_months = {
    1: "睦月", 2: "如月", 3: "弥生", 4: "卯月", 5: "皐月", 6: "水無月",
    7: "文月", 8: "葉月", 9: "長月", 10: "神無月", 11: "霜月", 12: "師走"
}

born_month = int(input("生まれた月を入力してください。旧暦の月名に変換します。(1-12)"))
print(old_months.get(born_month, "1 から 12までの数字を半角英数で入力してください"))

目次に戻る

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?