This question already has answers here:
How to test multiple variables against a value?
(24个答案)
两年前关闭。
此代码始终返回
相当于
所以
你可以用
或者更好
或
相反。
另一种获得相同结果的方法是使用
(24个答案)
两年前关闭。
if month == 1 or 10:
month1 = 0
if month == 2 or 3 or 11:
month1 = 3
if month == 4 or 7:
month1 = 6
if month == 5:
month1 = 1
if month == 6:
month1 = 4
if month == 8:
month1 = 2
if month == 9 or 12:
month1 = 5
此代码始终返回
month1
等于5
。我是编程新手,我做错什么了?(我想这涉及到一个事实,即12是最高的数字,但==
意味着等于正确的数字?) 最佳答案
编辑:我首先给出了这个不起作用的错误原因。正如其他人所指出的,
if month == 1 or 10:
# ...
相当于
if (month == 1) or 10:
# ...
所以
...
总是被执行。你可以用
if month in (1, 10):
month1 = 0
或者更好
a = [0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5]
month1 = a[month - 1]
或
d = {1: 0, 2: 3, 3: 3, 4: 6, 5: 1, 6: 4,
7: 6, 8: 2, 9: 5, 10: 0, 11: 3, 12: 5}
month1 = d[month]
相反。
另一种获得相同结果的方法是使用
datetime
模块:from datetime import datetime
month1 = (datetime(2011, month, 1) - datetime(2011, 1, 1)).days % 7
关于python - 为什么这个字符串总是最大可能的数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4986756/
10-09 22:33