获取错误:“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 是一个 int 而不是 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...")
,

如果您在顶部写:scoreinput = int(input('Score lesson: ')),则无需验证 scoreinput 是数字还是字母。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...