【问题标题】:TypeError: 'int' object is not iterable in while loopsTypeError:'int' 对象在 while 循环中不可迭代
【发布时间】:2018-02-18 02:37:47
【问题描述】:

我需要一些快速帮助, 我一直有这个问题: 第 8 行的“TypeError:'int' 对象不可迭代” 在这段代码中:

sold = 0
max = 0

for i in range(0,5):
    print ("Scout",(i+1),"> ",end="")
    x = int(input())
    sold = sold + x
   for i in x:
       if i > max:
           max = i
print (max)

谁能帮我帮我重新安排一下?我试图让 python 从值 x 中找到最大值。

【问题讨论】:

  • 您将输入转换为整数并将其分配给x。 2 行之后,您尝试从x 中逐一检索每个对象。但是整数应该有什么对象呢?
  • 你为什么有两个i?您应该将第二个 i 变量更改为其他变量以避免代码混淆。
  • for i in range()for i in x - 在哪里看到问题?阅读您编写的代码。还请阅读错误消息中的文字:第 8 行的 'int' object is not iterable" - 它们会准确地告诉您问题出在哪里以及问题的确切位置。该消息不存在只是占用屏幕空间。
  • 投反对票:您的问题标题询问“while”循环,但您的代码是“for”循环。 2个不同的东西!浪费时间

标签: python python-3.x int


【解决方案1】:

如何将值添加到这样的列表中:

nums = [] 

然后代替

x = int(input())

nums.append(int(input())

那就试试吧

for x in nums:
    If x > max:
        max = x

并确保您的缩进正确。在 python 中,缩进决定了代码是否运行,即使缩进减一,也会产生错误或意外的副作用。

【讨论】:

    【解决方案2】:

    这就是我重新排列的方式

    v = []  # create a list where you can store all the values
    for i in range(5):
        print("Scout {} > ".format(i + 1), end="")
        v.append(int(input()))  # read it and append it to the end of the list
    print(max(v))  # your 'max' variable
    print(sum(v))  # your 'sold' variable
    

    请注意,命名变量max 通常是个坏主意,因为它会覆盖我刚刚使用的内置函数。

    【讨论】:

    • 您的代码似乎正确,但我在第 5 行遇到了一个问题,它说“int”对象不可调用。
    • 您问“谁能帮我帮我重新安排一下?”。我选择了后者。
    【解决方案3】:

    这是您的代码的缩短版和工作版:

    v = [int(input("Scout {} > ".format(i + 1))) for i in range(5)]
    print('max: {}'.format(max(v)))
    print('sold: {}'.format(sum(v)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2023-01-22
      相关资源
      最近更新 更多