【问题标题】:How to solve TypeError: 'int' object is not iterable?如何解决 TypeError: 'int' object is not iterable?
【发布时间】:2018-06-29 13:57:10
【问题描述】:

我想在这个程序中做的是,我尝试进行一些输入并检查它们是偶数还是奇数,然后打印出来。但是,当我运行它时,它显示以下错误消息 - (见下图)

for i in inp: TypeError: 'int' object is not iterable

源代码:

def number():
    n=int(input('How many numbers are there in your input: '))
    for inp in range(n):
        inp=eval(input('input= '))
    for i in inp:
        if i % 2 == 0:
            print(i, ' is even')
            continue
        else:
            print(i, ' is odd')
            continue
number()

【问题讨论】:

标签: python python-3.x iteration typeerror


【解决方案1】:

您需要使用listappend 输入。这样你以后可以迭代它。

 def number():
    n = int(input('How many numbers are there in your input: '))
    inp = []
    for i in range(n):
        p = input('input= ')
        if p.isdigit():
            inp.append(int(p))
    for i in inp:
        if i % 2 == 0:
            print(i, ' is even')
        else:
            print(i, ' is odd')

number()

【讨论】:

    【解决方案2】:
    def number():
      n=int(input('How many numbers are there in your input: '))
      inp = []
      for i in range(n):
        inp.append(int(input('input= ')))
      for i in inp:
        if i % 2 == 0:
            print(i, ' is even')
    
        else:
            print(i, ' is odd')
    
    number()
    

    【讨论】:

    • 如果输入是02 而不是2,则使用eval() 将导致错误,因为它用于评估表达式,而int() 用于类型转换。在这种情况下还需要使用continue 吗? refered this
    猜你喜欢
    • 1970-01-01
    • 2019-04-12
    • 2016-02-18
    • 2022-11-02
    • 2017-10-14
    • 2020-11-07
    • 2016-01-09
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多