python废柴自学,请问变量中数据如何用or连接

(https://img-mid.csdnimg.cn/release/static/image/mid/ask/685855409676188.jpg )
请问为什么4月会显示31天呢😢

逻辑有一个问题。在 elif 语句中,判断月份的表达式“month == 1 or 3 or 5 or 7 or 8 or 10 or 12”是不正确的,因为这会被解释为“如果 month 等于1,或者3为真,或者5为真......”,这不是你想要的。你应该写成“month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12”这样的形式。

在这段代码中,第二个if语句的条件写法是错误的,它会被解析为:

elsif (month == 1) or (3) or (5) or (7) or (8) or (10) or (12):

这是因为在Python中,非零数字都被视为True,所以条件判断中的数字3被视为True,所以这个if语句实际上相当于:

if month == 1 or True or True or True or True or True or True:

这样,无论输入的是什么数字,都会被判断为31天。要正确地写出这个条件语句,应该将每个月份都写成一个判断条件,例如:

if month == 2:
    print("29days")
elif month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
    print("31days")
else:
    print("30days")

或者使用 in 关键字来判断月份是否在一个列表中:

if month == 2:
    print("29days")
elif month in [1, 3, 5, 7, 8, 10, 12]:
    print("31days")
else:
    print("30days")