在Python 3中转到 [英] Go to in Python 3
问题描述
Python 3没有GOTO或类似的东西.但是我有一些算法,需要GOTO类型的功能. 可能有人可以建议出路吗?
Python 3 have no GOTO or something like this. But I have some algoritm, that need GOTO type functionality. May be someone can suggest way out?
主菜单
1-新游戏 2选项 3退出
1-New Game 2-Options 3-Exit
用户操作-进入主菜单-进入选项菜单-再次进入主菜单,依此类推.因此,在代码中,我不知道如何通过主菜单返回并传送到上层代码.
User actions - enter to main menu - enter to options menu - enter to main menu AGAIN and so on. So in code I don't know how turn back and teleport to upper code with main menu.
推荐答案
您可以使用字典:'用户选择'->'相应操作',例如:
You could use a dictionary: 'user choice' -> 'corresponding action' e.g.:
import sys
def foo():
print('foo')
actions = {'1': foo, '2': sys.exit}
def read_choice(choices, prompt):
c = None
while c not in choices:
c = input(prompt)
return c
while True:
# get user input
x = read_choice(actions, 'Input 1 to do foo or 2 to exit')
actions[x]() # act on it
请参见完整示例,该示例还显示了如何从配置文件动态创建菜单.
See complete example that also shows how to create menu dynamically from a configuration file.
这篇关于在Python 3中转到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!