3

对不起,如果我只是愚蠢,但我是 python 新手。当我执行此操作并输入一个大于 7 的数字时,它会给出 5、6 和 7 的答案,并打印 > 7。它告诉我,“我希望它越过边界变成真棒”,然后是“太棒了”。PS我正在使用Python 3

print ('What is your name?')
LeName = input ()
print (' How are you, ' + LeName + '?')
print ('On a scale of one to ten, what would you rate your day so far?')
mood = int (input())
if mood <4:
    print ('That\'s horrible, I hope it gets better.')
if mood == '5' '6' or '7':
    print('Hope it crosses the border into awesome! :)')
if mood > 7:
    print('That\'s awesome!')
print ()

发布后大约 1/2 小时,我考虑了一下,然后将 if mood == '5' '6' of '7' 更改为 if mood >= and mood < 8。但我仍然很好奇为什么会发生这种情况。谢谢你的回答。

4

2 回答 2

12

这个说法:

if mood == '5' '6' or '7':

被解析为:

if (mood == '56') or '7':

这实际上只是if '7'或者if True因为类型是而类型mood是。int'56'str

发生的事情是 python 正在应用自动字符串连接'5' '6'将其转换为'56'. 它不等于,mood因为and和类型永远不会比较相等。所以,你有. but是一个类似于 true 的值,因此该块将始终执行。您可能想要的更像是:moodintintstrif False or '7''7'

if mood < 4:
   ...
elif 5 <= mood <= 7:
   ...
else:
   ...

我使用运算符链接来做我认为你正在尝试的事情。

于 2013-04-19T03:55:20.273 回答
0

使用元组很容易:

if mood in (5, 6, 7):
于 2013-04-19T03:59:39.300 回答