簡體   English   中英

為什么使用!=運算符會在我的python程序中給我一個簡單的錯誤?

[英]Why is using the != operator gives me a simple 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)

如果我輸入字母L或R或S,它會prints Sorry, I didn't understand that

預先感謝您的幫助!

您的邏輯有誤,這些if之一將始終匹配,因此它將始終打印出我不了解的內容。

如果字母不是“ L”,則第一個if將觸發,如果第二個將觸發。

您想要的是:

if turning != 'L' and turning != 'R' and turning != 'S':
    print "Sorry, I didn't understand that"

或更好:

if turning in ['L', 'R', 'S']:
    # do stuff for turning
else:
    print "Sorry, I didn't understand that"

您的邏輯存在缺陷。 如果輸入字母“ L”,則第一個if條件的評估結果為False,這很好,但是接下來的if條件將評估為True,這當然不是您想要的! 如果您仔細考慮,輸入的任何字符將始終滿足以下條件之一。

您真正想要的是以下內容:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM