我是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(这是大学任务)。它现在正在工作,非常感谢!
答案 0 :(得分:0)
如果您使用的是python 2,请更改:
ans = input("What would you like to do now?")
为:
ans = raw_input("What would you like to do now?")
raw_input
返回一个字符串,而输入返回integer
这在python 3中被更改,在3中只有input
并且它返回一个字符串
所以,如果您使用的是python 2,请将其更改为raw_input
,然后调用您的其他条件:
if int(ans) == 1:
main_loop()
break
答案 1 :(得分:0)
将最后的elif条件更改为elif not ans
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 not ans:
print("\nDo you not speak Latin, slave?")
编辑:答案是针对python 3的。 对于python 2.7,使用raw_input而不是input,并相应地使用int(ans)或字符串文字。
答案 2 :(得分:0)
使用raw_input
代替input
。 input
将尝试评估输入,评估空字符串会引发错误。 raw_input
没有评估,只给你一个字符串。请参阅this explanation。
def main_loop():
pass
def instructions_loop():
pass
def gauntlet_loop():
pass
def end_game_loop():
pass
next_loop_func = {
'1': main_loop,
'2': instructions_loop,
'3': gauntlet_loop,
'4': end_game_loop,
}
def menu_loop():
while True:
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 = raw_input("What would you like to do now?")
if ans in next_loop_func:
next_loop_func[ans]
else:
print("\nDo you not speak Latin, slave?")
menu_loop()