【问题标题】:Using prompt to determine which function to use使用提示来确定使用哪个函数
【发布时间】:2014-05-16 03:53:12
【问题描述】:

主函数调用之前定义的两个函数:“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()

【问题讨论】:

  • 你用的是哪个版本的python?\
  • prompt 在 Py3k 中始终为 str,将其与 int 进行比较将始终为您提供 False

标签: python function prompt


【解决方案1】:

如果您使用的是 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]

【讨论】:

    猜你喜欢
    • 2021-11-11
    • 2016-12-21
    • 2021-10-09
    • 2010-10-02
    • 2010-11-19
    • 1970-01-01
    • 2010-12-19
    • 2015-03-02
    • 1970-01-01
    相关资源
    最近更新 更多