gpt4 book ai didi

python - 如何将空输入算作 else

转载 作者:行者123 更新时间:2023-11-28 19:23:25 25 4
gpt4 key购买 nike

我是 Python 的新手,正在上课。下面是我的代码。我的问题是在我想要的最后一行,这样如果有人简单地按下回车键,它将被视为有人输入了(1/2/3 或 4)以外的输入,这基本上会用最后一个 elif 回复并重新开始问题.但此刻它给了我这个:

SyntaxError: unexpected EOF while parsing. 

有人可以帮忙吗?

def menu_loop():
ans = True
while ans:
print("""
1. My freedom awaits me, give me my blade!
2. I've never fought before, might you help me?
3. I have already forsaken freedom, I will fight till the death.
4. Fighting is for the wicked. I refuse to fight.

Press enter to quit
""")

ans= input("What would you like to do now?")
if ans == 1:
main_loop()
break
elif ans == 2:
instructions_loop()
break
elif ans == 3:
gauntlet_loop()
break
elif ans == 4:
print("\nMen... come relieve this man of his life.")
time.sleep(2)
end_game_loop()
break
elif ans == '':
print("\nDo you not speak Latin, slave?")

谢谢,感谢 Christian,我找到了答案。我想我从中获得说明的网站是关于 Python 3 的,而我在 2(这是为了大学作业)。现在可以使用了,非常感谢!

最佳答案

如果您使用的是 python 2,则更改:

ans = input("What would you like to do now?")

到:

ans = raw_input("What would you like to do now?")  

raw_input 返回一个字符串,而 input 返回一个 integer 这在 python 3 中改变了,在 3 中只有 input 并且它返回一个字符串

因此,如果您使用的是 python 2,请将其更改为 raw_input,然后像这样调用您的其他条件:

if int(ans) == 1:
main_loop()
break

关于python - 如何将空输入算作 else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19083963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com