【问题标题】:Getting Error : 'int' object has no attribute 'isnumeric'出现错误:“int”对象没有属性“isnumeric”
【发布时间】:2021-04-17 09:59:24
【问题描述】:

我正在编写代码来获取学生的平均成绩,但出现了错误。 这是我的一段代码出错:

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

请帮助我。谢谢

【问题讨论】:

  • 我无法重现此内容。可能的原因是您在 2.x 下运行代码,或者您在其他地方重新定义了input

标签: python if-statement integer do-while isnumeric


【解决方案1】:

如果输入是小于20的正数,这就是你想要的,在scoreinput=int(scoreinput)之后 你有数字,但你没有做某事,而是继续进行 while 循环的下一次迭代。在下一次迭代中,scoreinputint 而不是 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...")

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 2014-03-30
      • 2020-05-25
      • 2016-07-31
      • 2022-07-22
      • 2019-11-18
      相关资源
      最近更新 更多