这就是我正在努力的一点是/不是问题。
print("Hello")
print("I love you")
answer = input("Do you love me?")
if answer in ["yes"]:
print("Yey! I knew it! Thank You!")
if answer in ["no"]:
print("O-ok, I understand, no worries.")
while True:
try:
print("Please answer me.")
answer = input("Do you love me?")
except ValueError:
continue
if answer in ["yes", "no"]:
break
当我输入一个有效的答案时,它打印出我想要的内容,但也会再次跳入循环,如果我再次回答,那么它会中断。我不明白为什么。 当我输入一个无效的答案时,它会一直循环直到它得到一个正确的答案,当它一个正确时它会中断而不会答案。有人可以解释一下原因吗?
以下是我目前正在测试的地方:https://trinket.io/python/5a25117b84
答案 0 :(得分:1)
while循环的位置不对。如果您想再次询问答案是否无效,请尝试这样:
print("Hello")
print("I love you")
answer = input("Do you love me?")
while True:
try:
if answer == "yes":
print("Yey! I knew it! Thank You!")
break
elif answer == "no":
print("O-ok, I understand, no worries.")
break
else:
print("Please answer me.")
answer = input("Do you love me?")
except ValueError:
continue
答案 1 :(得分:0)
通过您的代码,它的工作方式应该如何。看,这部分代码回答了第一个问题("你爱我吗?"):
#
# First part of your code
#
print("Hello")
print("I love you")
answer = input("Do you love me?")
if answer in ["yes"]:
print("Yey! I knew it! Thank You!")
if answer in ["no"]:
print("O-ok, I understand, no worries.")
在你回答之后你会跳过"跳过"进入代码的第二部分("循环再次询问"):
#
# Second part of your code
#
while True:
try:
print("Please answer me.")
answer = input("Do you love me?")
except ValueError:
continue
if answer in ["yes", "no"]:
break
您需要删除/删除代码的第二部分。部分循环/循环:
while True:
try:
print("Please answer me.")
answer = input("Do you love me?")
except ValueError:
continue
if answer in ["yes", "no"]:
break
或者你可以使用一个循环,一个很好的例子就是来自Ni3_k的答案。