[英]Why is using the != operator gives me a simple error in my python program?
Why using the != operator produces an error in my python program 为什么使用!=运算符会在我的python程序中产生错误
def TakeTurn():
time.sleep(1.5)
turning = input("You have reached a junction.\nDo you want to turn left (L), turn right (R) or go straight ahead(S)?")
if turning != "L" :
print ("Sorry, I didn't understand that")
elif turning != "R" :
print ("Sorry, I didn't understand that")
elif turning != "S" :
print ("Sorry, I didn't understand that")
else:
choice = randint (1,10)
print (choice)
If I enter the letter L or R or S it prints Sorry, I didn't understand that
如果我输入字母L或R或S,它会
prints Sorry, I didn't understand that
Thank you in advance for the help !!! 预先感谢您的帮助!
Your logic is faulty, one of these ifs will always match, so it will always print I didn't understand. 您的逻辑有误,这些if之一将始终匹配,因此它将始终打印出我不了解的内容。
If the letter is not 'L' the first if will trigger, if it is the second will trigger. 如果字母不是“ L”,则第一个if将触发,如果第二个将触发。
What you want is: 您想要的是:
if turning != 'L' and turning != 'R' and turning != 'S':
print "Sorry, I didn't understand that"
or better yet: 或更好:
if turning in ['L', 'R', 'S']:
# do stuff for turning
else:
print "Sorry, I didn't understand that"
There is a flaw in your logic. 您的逻辑存在缺陷。 If you enter the letter "L", the first if condition will evaluate to False, which is good, but then the next if condition will evaluate to True, which is certainly not what you want!
如果输入字母“ L”,则第一个if条件的评估结果为False,这很好,但是接下来的if条件将评估为True,这当然不是您想要的! If you think about it more carefully, any character you enter will always meet one of these conditions.
如果您仔细考虑,输入的任何字符将始终满足以下条件之一。
What you really want is the following: 您真正想要的是以下内容:
if turning not in ["L", "R", "S"]:
print ("Sorry, I didn't understand that")
else:
choice = randint (1,10)
print(choice)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.