2017-04-07 36 views
0

當我運行代碼時,它要求用戶輸入3次,但是當條件滿足時,它仍然只打印其中的2個。爲什麼?我對Python很陌生,但在谷歌上看到任何答案都很瘋狂,但我仍然感到困惑。在while循環中分配後只有兩個變量

name = raw_input("Name your age: ") 
print ("3 choices.") 
key = raw_input("What will this world have?: ") 

def generator(): 
    data = 1 
    choice1 = "" 
    choice2 = "" 
    choice3 = "" 
    while(data != 3): 
     key = raw_input("What will this world have?: ") 
     data += 1 
     if (key == "grass"): 
       choice1 = "The world is covered in green grass." 
     elif (key == "water"): 
       choice2 = "The world is covered in water." 
     elif (key == "sky"): 
       choice3 = "The sky is vast and beautiful." 
     if (data >= 3): 
      print("Before you is " + name) 
      print(choice1) 
      print(choice2) 
      print(choice3) 
      raw_input("Press Enter to continue...") 
     else: 
      print("Invalid Option") 


generator() 
+0

你增加'data'計數的用戶輸入後,無論如果它是一個有效的選擇與否。如果你只在* if內增加'data'('data + = 1'),那麼你只能計算有效的數據' – davedwards

回答

0

這個問題是因爲你在1開始data。 用戶,然後進入他們的第一選擇,而你增加data爲2 用戶接着輸入錫爾第二個選擇,你,你增加data到3

因爲data現在3,它執行你的if data >= 3聲明, 和僅打印choice1choice2,因爲用戶還沒有給出他們的第三選擇。

如果你設置:

data = 0 

在開始,而不是:

data = 1 

然後用戶必須輸入他們的第三個選擇,你希望它會工作。

更新 要停止打印invalid choice一切的時候,你需要從這裏移動你的其他的位置:

if (data >= 3): 
     print("Before you is " + name) 
     print(choice1) 
     print(choice2) 
     print(choice3) 
     raw_input("Press Enter to continue...") 
    else: 
     print("Invalid Option") 

到這裏:

if (key == "grass"): 
     choice1 = "The world is covered in green grass." 
    elif (key == "water"): 
     choice2 = "The world is covered in water." 
    elif (key == "sky"): 
     choice3 = "The sky is vast and beautiful." 
    else: 
     print("Invalid Option") 

,否則會打印Invalid Option每次循環執行和data < 3

此外,如果您選擇一個無效的選項,它會弄亂你的data計數器。我建議把一個遞增data行:

while(data != 3): 
    key = raw_input("What will this world have?: ") 
    if (key == "grass"): 
     choice1 = "The world is covered in green grass." 
    elif (key == "water"): 
     choice2 = "The world is covered in water." 
    elif (key == "sky"): 
     choice3 = "The sky is vast and beautiful." 
    else: 
     print("Invalid Option") 
     continue # this will skip the rest of the loop if the option is invalid 

    data += 1 # only increment if the option in valid 
    if (data >= 3): 
     print("Before you is " + name) 
     print(choice1) 
     print(choice2) 
     print(choice3) 
     raw_input("Press Enter to continue...") 
+0

我在原始代碼中試過這個提示三個輸入。當我嘗試編輯時,當我輸入第二個選項時它仍然顯示無效選項,並且只打印選擇2和選擇3。任何其他想法?儘管謝謝你的回覆。 –

+0

當你說'無效選擇'時,你輸入了什麼?您可能會對'key = raw_input'感到困惑,因爲它不在函數中,它沒有做任何事情,因此您應該將其刪除。 –

+0

哇大聲確定我刪除了,並設置數據像建議,現在它完美的作品!我感覺啞巴哈哈謝謝你! :) –