python - 出现错误:“int”对象没有属性“isnumeric”
问题描述
我正在编写代码以获取学生的平均成绩,但出现错误。这是我的一段代码出错:
scoreinput=input("Score lesson: ")
while True:
if scoreinput.isnumeric():
scoreinput=int(scoreinput)
if scoreinput > 20:
scoreinput = int(input("This number is too big. Try again: "))
elif scoreinput < 0:
scoreinput = int(input("This number is too low. Try again: "))
else:
print("please write number correctly...")
这是此代码的输出,但出现错误:
Score lesson: 5
Traceback (most recent call last):
File "e:\TEST PYTHON\test3.py", line 3, in <module>
if scoreinput.isnumeric():
AttributeError: 'int' object has no attribute 'isnumeric
请帮我。谢谢
解决方案
如果输入是一个小于 20 的正数,这就是你想要的,在scoreinput=int(scoreinput)
你得到这个数字之后,你不会做任何事情,而是继续进行 while 循环的下一次迭代。在下一次迭代中,scoreinput
is anint
而不是str
这就是您收到错误的原因。如果scoreinput
在正确的范围内,您应该使用break
停止循环。
当输入错误时会出现另一个问题。如果输入不是数字,则您不会获得新的输入,并且会陷入无限循环。如果输入是一个数字,但不在 0 到 20 之间,您将获得新输入并立即将其转换为int
. 如果输入不是数字,则会出现异常。如果它是一个数字,它会在你到达下一次迭代时立即失败,因为scoreinput
应该是str
在迭代的开始,但它会是int
.
我建议您使用以下代码:
while True:
scoreinput=input("Score lesson: ") # using input only one time at the beggining of the loop instead of input command for each case of bad input
if scoreinput.isnumeric():
scoreinput=int(scoreinput)
if scoreinput > 20:
print("This number is too big. Try again.")
elif scoreinput < 0:
print("This number is too low. Try again.")
else:
break # input is valid
else:
print("please write number correctly...")
推荐阅读
- graph - 图中所有对的最短路径均指向非负加权边
- typescript - 扩展接口问题 Typescript/js
- laravel - Laravel 5.8 手动用户批准?
- jquery - 如何使用 JS 下载文件作为操作方法的结果(.NET Core 2 MVC)
- git - Git检测壁球和合并分支
- c# - 使用包含纯文本版本的 Amazon SES 使用 C# 发送 HTML 电子邮件
- mysql - 如何查找除最近条目之外的所有条目的重复和更新列值
- typescript - 打字稿可选参数中断查询
- vue.js - 在 vue-router 中嵌套类似路由不渲染深层组件
- c - 对指针的后缀一元自增操作