gpt4 book ai didi

python-3.x - 有没有办法缩短python中的if-elif-else语句?

转载 作者:行者123 更新时间:2023-12-05 00:43:36 25 4
gpt4 key购买 nike

我刚开始学习 python,我用 if 语句做了一些代码,我认为代码中有太多 elif 语句,所以我想知道是否有什么办法可以缩短代码。

from random import *
month = randrange(1, 13)
if month == 1:
print("January")
elif month == 2:
print("February")
elif month == 3:
print("March")
elif month == 4:
print("April")
elif month == 5:
print("May")
elif month == 6:
print("June")
elif month == 7:
print("July")
elif month == 8:
print("August")
elif month == 9:
print("September")
elif month == 10:
print("October")
elif month == 11:
print("November")
else:
print("December")

最佳答案

您可以将月份放在一个列表中并通过随机索引访问它:

from random import *
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'Augsut', 'September', 'October', 'November', 'December']
month = randrange(12)
return months[month]

关于python-3.x - 有没有办法缩短python中的if-elif-else语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69145533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com