Python - 新手 : Why this simple if-elif (replication of the C case block) always produces the same result?

标签 python if-statement

这里是初学者。每当我输入指定的字符串时,任何人都可以解释和/或帮助我修改此 Python 代码以生成正确的输出吗?例如,如果输入 March,则输出“02”。目前,程序始终输出 00,表示一月,无论输入如何。这是代码:

x = raw_input("Starting Month: ")

if x == "January" or "january":
   stMonth = '00'
elif x == "February" or "february":
    stMonth = '01'
elif x == "March" or "march":
    stMonth = '02'
elif x == "April" or "april":
    stMonth = '03'
elif x == "May" or "may":
    stMonth = '04'
elif x == "June" or "june":
    stMonth = '05'
elif x == "July" or "june":
    stMonth = '06'
elif x == "August" or "august":
    stMonth = '07'
elif x == "September" or "september":
    stMonth = '08'
elif x == "October" or "october":
    stMonth = '09'
elif x == "November" or "november":
    stMonth = '10'
elif x == "December" or "december":
    stMonth = '11'
else:
    print "error"
print stMonth

输出:

$ python month.py 
Starting Month: march
00

提前致谢 - 非常非常感谢您的帮助!

最佳答案

因为 or优先级高于 == : x == 'january' or 'January'实际上与 (x == 'january') or 'January' 相同, 以及 'January'评估为 true ,组合语句始终为真。

您应该将每个语句更改为 x == 'january' or x == 'January' .

关于Python - 新手 : Why this simple if-elif (replication of the C case block) always produces the same result?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27728687/

相关文章:

Python Xlib.error.BadAccess 尝试访问 X11 快捷键

python - python中使用key对数据进行排序

python - 散点图中的黑点

python - Jinja 按字母顺序对大小写混合的列表进行排序

python - python 中的 NumPy ImportError - Dll 加载失败

c++ - C++ 中的无分支 if 是什么样子的?

PowerShell:如果未找到字符串,则会出现不必要的错误

MYSQL INSERT 基于 3 列的值

java - 比较应该返回 true,但返回 false

java - 我得到一个 else 没有 if 错误,我不明白为什么 - JAVA