python请求用户输入有效参数

CodeDeveloper 程序熵 2023-05-21 17:53 发表于北京


问:

我正在编写一个接受用户输入的程序。

#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`age = int(input("Please enter your age: "))if age >= 18:     print("You are able to vote in the United States!")else:    print("You are not able to vote in the United States.")

只要用户输入有意义的数据,程序就会按预期工作。

Please enter your age: 23You are able to vote in the United States!

但是,如果用户输入无效数据就会失败:

Please enter your age: dickety sixTraceback (most recent call last):  File "canyouvote.py", line 1, in <module>    age = int(input("Please enter your age: "))ValueError: invalid literal for int() with base 10: 'dickety six'

我希望程序再次请求输入,而不是崩溃。像这样:

Please enter your age: dickety sixSorry, I didn't understand that.Please enter your age: 26You are able to vote in the United States!

如何请求有效输入而不是崩溃或接受无效值(例如-1)?



答:

题主的描述表明在输入无效数据时,程序抛出了异常,为了应对异常而不让程序崩溃,我们可以使用前文 Python 控制流之 try-except和finally语句写过的 try-except 语句。示例代码如下:

while True:    try:        age = int(input("Please enter your age: "))    except ValueError:        print("Sorry, I didn't understand that.")        continue    else:        #inut data is valid.        #now, we can exit the loop.        breakif age >= 18:    print("You are able to vote in the United States!")else:    print("You are not able to vote in the United States.")


进一步,要想使代码更简洁,可以采用 Python 库 click。

Click 是一个利用很少的代码以可组合的方式创造优雅命令行工具接口的 Python 库。它致力于将创建命令行工具的过程变的快速而有趣。我们可以编写如下代码实现题主的需求:

import click
age = click.prompt('Please enter your age', type=int)if age >= 18: print("You are able to vote in the United States!")else: print("You are not able to vote in the United States.")







参考:

  • stackoverflow question 23294658

  • https://click.palletsprojects.com/en/8.1.x/prompts/#input-prompts




更多好文请关注↓




收录于合集 #python
 27
上一篇Python面向对象的基础三--私有变量

微信扫一扫
关注该公众号