2017-04-07 81 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

哇大声确定我删除了,并设置数据像建议,现在它完美的作品!我感觉哑巴哈哈谢谢你! :) –