当我运行代码时,它要求用户输入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()
答案 0 :(得分:0)
问题出现是因为您在data
处开始1
。
然后,用户输入他们的第一个选项,并将data
增加到2。
然后用户输入第二个选项,您将data
增加到3。
由于data
现在为3
,因此会执行您的if data >= 3
声明,
并且只打印choice1
和choice2
,因为用户还没有给出他们的第三个选择。
如果你设置:
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...")