用户输入的整数仅使用 type() == int

Lui*_*do 0 python

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
Run Code Online (Sandbox Code Playgroud)

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

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'
Run Code Online (Sandbox Code Playgroud)

输入整数时它工作正常。我试过isinstance()and is_integer(),但无法让它们工作,所以只是试图让它变得简单。

Chr*_*yle 5

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

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

因此,尝试转换为 int,如果可行,则中断循环,如果出现值错误,请告诉他们使用数字。

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

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