Python - 新手:为什么这个简单的 if-elif(C case 块的复制)总是产生相同的结果?

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

这里是初学者。谁可以解释 and/or 帮助我修改这个 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

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

那是因为 "january" 的计算结果为 True,检查一下:

In [1]: x = 'march'

In [2]: if x == "January" or "january":
   ...:        stMonth = '00'
   ...:     

In [3]: stMonth
Out[3]: '00'

In [4]: bool("january")
Out[4]: True

你可能想要:

x == "January" or x == "january":
    stMonth = '00'

甚至更好:

x.lower() == "january":
    stMonth = '00'

它没有按预期工作的原因是,

if x == "January" or "january":

相当于:

if x == "January" or True:

并且第一个 if 语句将始终是 True

>>> x = 'january'
>>> if x:
...     print x
...     
january
>>> 

使用 .lower() 函数将输入字符串转换为小写,这会更容易。

x = raw_input("Starting Month: ").lower()

if x == "january":
   stMonth = '00'
elif x == "february":
    stMonth = '01'
elif x == "march":
    stMonth = '02'
elif x == "april":
    stMonth = '03'
elif x == "may":
    stMonth = '04'
elif x == "june":
    stMonth = '05'
elif x == "june":
    stMonth = '06'
elif x == "august":
    stMonth = '07'
elif x == "september":
    stMonth = '08'
elif x == "october":
    stMonth = '09'
elif x == "november":
    stMonth = '10'
elif x == "december":
    stMonth = '11'
else:
    print "error"
print stMonth

因为 or 的优先级高于 ==x == 'january' or 'January' 实际上与 (x == 'january') or 'January' 相同,并且 'January' 的计算结果为 true,组合语句始终为真。

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

为了消除您的疑问,请像这样修复您的代码:

if x == "January" or x == "january":
   stMonth = '00'
elif x == "February" or x == "february":
    stMonth = '01'

您的声明:

if x == "January" or "january":

总是返回真,因为它的计算结果为:

是 x == "January" 否 然后 or 被评估并检查 1 月并且它 returns 为真。所以如果你尝试: 如果 "january": 它总是 returns 你的真实,因此你得到 00 作为输出。

您可以使用 or 或 IN 子句,例如:

if x == "January" or x == "january":

if x in ("January", "january"):