2016-12-16 61 views
0

通常,當我編程和使用決策結構(以及原始輸入)時,我選擇的答案將被忽略,並轉到第一個「if」語句並顯示輸出。Python編程決策結構

在課堂上,我們必須創建一個使用循環和決策結構的遊戲。當我運行程序時,我一直遇到輸出'if'語句輸出的程序問題,而不是用戶選擇的答案。

例如;

score=0 
while True: 

    optionOne=raw_input("Please pick one of the options!") 


    if (optionOne=="one" or "One" or "ONE"): 
     print "You have succesfully sneaked out without alerting your parents!" 
     print "Your current score is " + str(score) 
     break 
    elif (optionOne=="two" or "Two" or "TWO"): 
     print "Due to stress from work, your mom does not notice your lies and allows you to leave." 
     print "Your current score is " + str(score) 
     break 
    elif (optionOne=="three" or "Three" or "THREE"): 
     print "Your mom is understanding and allows you go to the party!" 
     score=score+10 
     print "You get 10 additional points for being honest!" 
     print "Your current score is " + str(score) 
     break 

這裏,儘管用戶選擇第二個選項時,輸出爲先「如果」使用的語句。我很困惑我發生了什麼語法錯誤或錯誤。

回答

0

錯誤是在這裏: if (optionOne=="one" or "One" or "ONE"):

在Python空字符串(或序列)被認爲False而一個字符串(或序列與值)被認爲是True

>>> bool('') 
False 

>>> bool('One') 
True 

>>>'two'=='one' or 'One' or "ONE" 
'One' 

在上述比較'two'=='one'FalseFalse or 'One'將返回'One'這是True

這樣實現:

score=0 
while True: 

    optionOne=raw_input("Please pick one of the options!") 


    if (optionOne in ["one", "One", "ONE"]): 
     print "You have succesfully sneaked out without alerting your parents!" 
     print "Your current score is " + str(score) 
     break 
    elif (optionOne in ["two", "Two", "TWO"]): 
     print "Due to stress from work, your mom does not notice your lies and allows you to leave." 
     print "Your current score is " + str(score) 
     break 
    elif (optionOne in ["three", "Three", "THREE"]): 
     print "Your mom is understanding and allows you go to the party!" 
     score=score+10 
     print "You get 10 additional points for being honest!" 
     print "Your current score is " + str(score) 
     break 
0

你要做

if optionOne == "one" or optionOne == "One" or optionOne == "ONE": 

或更短 - 將文本轉換爲小寫

optionOne = optionOne.lower() 

if optionOne == "one": 
    # ... 
elif optionOne == "two": 
    # ... 

如果有不同的話,那麼你可以使用in

optionOne = optionOne.lower() 

if optionOne in ("one", "1"): 
    # ... 
elif optionOne in ("two", "2"): 
    # ... 

BTW:代碼

if optionOne=="one" or "One" or "ONE": 

被視爲

if (optionOne == "one") or ("One") or ("ONE") 

"One"(和"ONE")作爲True處理,使你有

if (optionOne == "one") or True or True: 

永遠是True