使用prompt来确定要使用的函数

2024-04-19 21:33:27 发布

您现在位置:Python中文网/ 问答频道 /正文

主函数调用了前面定义的两个函数:“reg()”和“usa()”
我希望用户能够决定运行哪个函数。
但是,即使选择了“1”,仍然会运行“usa()”

def main():
    prompt = (input("If you would like to change the regional market numbers,
                     press 1."
                    "If you would like to change the national market, press 2."))
    if prompt == 1:
        a = reg()
        a
    else:
        b = usa()
        b


main()

Tags: theto函数youifmainregchange
1条回答
网友
1楼 · 发布于 2024-04-19 21:33:27

如果您使用的是Python 3,那么input()将返回一个字符串,与整数比较时,该字符串将始终返回false。无需使用if和else语句来决定使用哪个函数:

def main():
    functions = {1: reg, 2: usa}
    prompt_message = 'If you would like to change the regional market numbers, press 1.\nIf you would like to change the national market, press 2.'
    prompt = str(input(message))
    function = functions[prompt]

相关问题 更多 >