Go to in Python 3

旧城冷巷雨未停 提交于 2019-12-08 09:46:02

问题


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?

Main menu

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.


回答1:


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.



来源:https://stackoverflow.com/questions/13442440/go-to-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!