Go to in Python 3

2019-06-13 17:58发布

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条回答
疯言疯语
2楼-- · 2019-06-13 18:14

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.

查看更多
登录 后发表回答