python - 仅使用 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()
,但无法让它们工作,所以只是试着让它变得简单。
解决方案
有多种方法可以解决此问题。首先,您的错误是因为您试图将字符串转换为 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")
推荐阅读
- java - 使用 Gson 出现 MalformedJsonException 错误
- sql - SQL中的外键到数据透视表 - 数据库设计
- c - Switch case 不会继续下一条语句
- r - 在一个图中可视化两个非常不同的分布
- ios - IOS app打开onesignal通知会崩溃
- regex - nginx 位置使用任何子域和任何路径重定向除特定域之外的所有域
- vue.js - 如何从 pageAction 弹出窗口中打开 browserAction 弹出窗口?
- ruby-on-rails - 使用 ROR 和 mongoid 进行分页
- spring-data-jpa - QuerySyntaxException:期待关闭,在第 1 行附近发现“空”
- dataframe - 在火花数据帧中生成哈希键(数据帧中的唯一标识符列)