首页 > 解决方案 > 仅使用 type() == int 的整数用户输入

问题描述

a = False
while a == False:
    quant = int(input("Input the size:\n"))
    if type(quant) == int:
        a = True
    else:
        print('Please use numbers:\n')
        a = False

我试图让用户无法输入字符,但如果他们这样做,它会打印出第二条消息。但是,当我尝试输入字符时,会出现以下消息:

Traceback (most recent call last):
  File "C:/Users/user/Desktop/pythonproject1/Actual Projects/password 
generator/Password_generator.py", line 34, in <module>
    quant = int(input("Input the:\n"))
ValueError: invalid literal for int() with base 10: 'thisiswhatIwrote'

输入整数时效果很好。我试过isinstance()and is_integer(),但无法让它们工作,所以只是试着让它变得简单。

标签: python

解决方案


有多种方法可以解决此问题。首先,您的错误是因为您试图将字符串转换为 int。当字符串有字符时,这些字符不能转换为 int,所以你会得到一个 ValueError。您可以利用此行为来验证输入

while True:
    try:
        quant = int(input("Input the size:\n"))
        break
    except ValueError as ve:
        print('Please use numbers:\n')

因此,尝试转换为 int,如果它可以打破循环,如果你得到一个值错误告诉他们使用数字。

或者,您可以将输入捕获为字符串,然后使用字符串方法 isumeric 来查看它是否为数字。如果是,则将其转换为数字并打破循环,否则告诉他们使用数字。

while True:
    quant = input("Input the size: ")
    if quant.isnumeric():
        quant = int(quant)
        break
    else:
        print("Please use numbers")

推荐阅读