在while循环中赋值后只打印两个变量

时间:2017-04-07 01:43:30

标签: python-2.7

当我运行代码时,它要求用户输入3次,但是当条件满足时,它仍然只打印其中2个。为什么?我是Python的新手,但是对于Google上的任何答案都疯狂地环顾四周,但我仍然感到困惑。

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()

1 个答案:

答案 0 :(得分:0)

问题出现是因为您在data处开始1。 然后,用户输入他们的第一个选项,并将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 Optiondata < 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...")