【问题标题】:Getting user input and making a decision获取用户输入并做出决定
【发布时间】:2013-07-02 09:28:23
【问题描述】:

我启动我的 python 脚本询问用户他们想做什么?

def askUser():
    choice = input("Do you want to: \n(1) Go to stack overflow \n(2) Import from phone \n(3) Import from camcorder \n(4) Import from camcorder?");
    print ("You entered: %s " % choice);

然后我想:

  1. 确认用户输入的内容有效 - 从 1 到 4 的单个数字。
  2. 根据导入跳转到对应的函数。类似于 switch case 语句。

关于如何以 Python 方式执行此操作的任何提示?

【问题讨论】:

  • 这是用于 Python 2 还是 3?

标签: python validation case


【解决方案1】:

首先,python 中不需要分号 :)(耶)。

使用字典。此外,要获得几乎肯定会在 1-4 之间的输入,请使用 while 循环继续请求输入,直到给出 1-4:

def askUser():
    while True:
        try:
            choice = int(input("Do you want to: \n(1) Go to stack overflow \n(2) Import from phone \n(3) Import from camcorder \n(4) Import from camcorder?"))
        except ValueError:
            print("Please input a number")
            continue
        if 0 < choice < 5:
            break
        else:
            print("That is not between 1 and 4! Try again:")
    print ("You entered: {} ".format(choice)) # Good to use format instead of string formatting with %
    mydict = {1:go_to_stackoverflow, 2:import_from_phone, 3:import_from_camcorder, 4:import_from_camcorder}
    mydict[choice]()

我们在这里使用try/except 语句来显示输入是否不是数字。如果不是,我们使用 continue 从头开始​​ while 循环。

.get() 使用您提供的输入从mydict 获取值。由于它返回一个函数,我们在后面加上() 来调用该函数。

【讨论】:

  • 您没有验证任何内容。如果用户输入“废话!”怎么办?代替?
  • 而实现开关的pythonic方式通常是使用字典调度程序。
  • 不,你把它移到别处了,但你没有处理它会抛出的任何异常。
  • 现在我们正在取得进展。 :-)
  • @MartijnPieters:D。感谢您的帮助!
猜你喜欢
  • 2018-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多