繁体   English   中英

出现错误:'int' object 没有属性 'isnumeric'

[英]Getting Error : 'int' object has no attribute '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...")

这是此代码的 output 出现错误:

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是数字还是字母。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM