具有多个值的python if语句求值
我不太清楚为什么,但当我执行这段代码时,什么都没有发生具有多个值的python if语句求值,python,Python,我不太清楚为什么,但当我执行这段代码时,什么都没有发生 while (True) : choice = str(input("Do you want to draw a spirograph? (Y/N) ")) if choice == 'n' or 'N' : break elif choice == 'y' or 'Y' : <CODE> else : print("Please e
while (True) :
choice = str(input("Do you want to draw a spirograph? (Y/N) "))
if choice == 'n' or 'N' :
break
elif choice == 'y' or 'Y' :
<CODE>
else :
print("Please enter a valid command.")
choice = input("Do you want to draw a spirograph? (Y/N)")
它不起作用,因为在
if
语句中,'N'
文本的计算结果总是True
您的if
条件当前为if-choice=='n'或'n':
,这相当于if(choice=='n')或('n')
,无论变量choice
的值如何,它都将求值为True
,因为文本'n'
总是求值为True
相反,请使用以下方法之一
如果choice='n'或choice='n':
如果选择“nN”:
如果在('n','n')中选择:
这同样适用于
elif
块。您可以阅读更多信息。此表达式不符合您的要求:
choice == 'n' or 'N'
其解释如下:
(choice == 'n') or 'N'
您可能希望尝试以下方法:
choice in 'nN'
编辑代码部分并在其中添加
行。我自己不这么做,因为你的问题可能依赖于它。在Python self-Lintted这种情况下,可以避免这么多问题..FWIW,你不需要在谓词周围加括号而True:
更好。的可能重复项(并查看重复项上的许多链接答案,如)