获取用户输入并做出决定

2024-04-25 22:08:38 发布

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

我启动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的方式来做这件事有什么建议吗?在


Tags: to用户fromimport脚本yougoinput
1条回答
网友
1楼 · 发布于 2024-04-25 22:08:38

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

使用字典。另外,要获得几乎肯定在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()从{}获取值,并提供输入。当它返回一个函数时,我们在后面放()来调用函数。在

相关问题 更多 >