python - 如何阻止非数字输入导致 Python 程序崩溃?

标签 python

我正在尝试为一个将进行对话的类(class)创建一个程序。我想强制用户为变量 your_agemy_age 输入 int。我做了很多研究,我尝试按照我相信我被告知的方式编写程序,但如果我输入“1”而不是“1”,程序就不会运行。如果用户输入“一”,我希望他们获得错误代码并有机会重新输入变量。

代码:

name = input('Salutations what is your name?') #user will input their name and it will be saved in the variable name
print('That is a nice name ' + name + ' whats your favorite color') #genorate a sentance using the variable name

color =input('') #this input is collecting the information from the above sentence
print (color + ' is a great color')#make user feel like they picked a good color

#your_age = int(input('How old are you?'))#user sets variable age
while True:
    your_age = int(input('How old are you?'))
    try:
        your_age = int(your_age)
        break
    except ValueError:
        print('INVALID: you can round up or down but please enter your age using digits')


my_age = int(input(' how old am I?'))

combine_age = str(your_age + my_age)
print ('Our combined age is ')
print (combine_age)

我运行了代码,但我进行了压力测试,发现如果我不输入数字,程序就会崩溃。我在 YouTube 和自动化无聊的东西中进行了研究,但找不到足够的答案。

最佳答案

您可以编写一个通用函数来获取用户的整数输入。

类似这样的事情:

def get_int(prompt: str) -> int:
    while True:
        s = input(prompt)
        try:
            return int(s)
        except ValueError:
            print('\aInvalid - try again')

print(get_int('Hello: '))

因此,无论您在哪里需要 int,只需在适当的提示下调用 get_int() 即可,您可以放心,您只会返回一个有效的 int

关于python - 如何阻止非数字输入导致 Python 程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77089742/

相关文章:

python - celery 错误电子邮件 : can not receive emails celery

python - 如何获得有关 Python 意外 SIGABRT 的更多信息?

python - 在 gridsearchcv sklearn 中提供训练和验证集

python - 从 pycurl 返回的字典中提取数据

python - 具有混合值的两列的唯一组合

python - 将 Python IDLE 设置为默认程序以打开 .py 扩展

Python OpenCV 立体校准对象点

python - Django 1.9 : Should I avoid importing models during `django.setup()` ?

Python:通过乘法运算符时间复杂度创建列表

python - 使用 Enigma Catalyst 检索 Bittrex 交换的分钟频率数据时出错