print(" You can see a faint outline of a coast in the distance... you can either: 1. paddle to the island on the raft ; 2. swim to the island")
option2 = input("> ")
while True:
if (option2 == "1"):
print("The raft fully sinks... you are left in the freezing cold water. You spent all your energy trying to keep the raft afloat. You have made your demise inevitable")
break
elif (option2 == "2"):
print("You jump headfirst into the cold water... not really a good idea, but you seem to have insane swimming skills. Are you Michael Phelps? Anyways you make it to the shore seconds before fainting")
else:
print(" Invalid input: Please select one of the options above") <---- It keeps printing this
continue
这是我使用的代码。我是 Python 新手,我真的不知道 while 循环是如何工作的
我尝试查找语法问题,但找不到任何问题
现在,如果您输入的选项不是“1”或“2”,它就会无限循环。您将进入 else 语句,其中包含“继续”关键字。
'继续'表示开始下一次迭代。只要您的选项仅被捕获一次(在循环之前),它就永远不会改变,因此您将始终陷入 else 块中。
为了使其工作,您需要将“option2 = input(">”)”移动到循环内部:
print("You can see a faint outline of a coast in the distance... you can either:\n1. paddle to the island on the raft;\n2. swim to the island;")
while True:
option2 = input("> ")
if option2 == "1":
print("The raft fully sinks... you are left in the freezing cold water. You spent all your energy trying to keep the raft afloat. You have made your demise inevitable")
break
elif option2 == "2":
print("You jump headfirst into the cold water... not really a good idea, but you seem to have insane swimming skills. Are you Michael Phelps? Anyways, you make it to the shore seconds before fainting")
break
else:
print("Invalid input: Please select one of the options above")
您可以在此处
了解有关 while 循环如何工作的更多信息您收到此错误是因为 while 循环不包含 while 循环的 elif 和 else 条件的退出条件。对于选项 1,您不会遇到此问题,因为它有一个中断条件,这将有助于从 while 循环中退出程序。因此,您还需要为 elif 和 else 添加中断。以下是添加的正确代码:
print(" You can see a faint outline of a coast in the distance... you can either: 1. paddle to the island on the raft ; 2. swim to the island")
option2 = input("> ")
while True:
if (option2 == "1"):
print("The raft fully sinks... you are left in the freezing cold water. You spent all your energy trying to keep the raft afloat. You have made your demise inevitable")
break
elif (option2 == "2"):
print("You jump headfirst into the cold water... not really a good idea, but you seem to have insane swimming skills. Are you Michael Phelps? Anyways you make it to the shore seconds before fainting")
break
else:
print(" Invalid input: Please select one of the options above")
break