int object is not iterable?

前端 未结 11 836
天命终不由人
天命终不由人 2020-12-01 11:19
inp = int(input(\"Enter a number:\"))

for i in inp:
    n = n + i;
    print (n)

... throws an error: \'int\' object is not iterable<

相关标签:
11条回答
  • 2020-12-01 11:40

    Well, you want to process the string representing the number, iterating over the digits, not the number itself (which is an abstract entity that could be written differently, like "CX" in Roman numerals or "0x6e" hexadecimal (both for 110) or whatever).

    Therefore:

    inp = input('Enter a number:')
    
    n = 0
    for digit in inp:
         n = n + int(digit)
         print(n)
    

    Note that the n = 0 is required (someplace before entry into the loop). You can't take the value of a variable which doesn't exist (and the right hand side of n = n + int(digit) takes the value of n). And if n does exist at that point, it might hold something completely unrelated to your present needs, leading to unexpected behaviour; you need to guard against that.

    This solution makes no attempt to ensure that the input provided by the user is actually a number. I'll leave this problem for you to think about (hint: all that you need is there in the Python tutorial).

    0 讨论(0)
  • 2020-12-01 11:43

    One possible answer to OP-s question ("I wanted to find out the total by adding each digit, for eg, 110. 1 + 1 + 0 = 2. How do I do that?") is to use built-in function divmod()

    num = int(input('Enter a number: ')
    nums_sum = 0
    
    while num:
        num, reminder = divmod(num, 10)
        nums_sum += reminder
    
    0 讨论(0)
  • 2020-12-01 11:45

    maybe you're trying to

    for i in range(inp)
    

    I just had this error because I wasn't using range()

    0 讨论(0)
  • 2020-12-01 11:45

    As ghills had already mentioned

    inp = int(input("Enter a number:"))
    
    n = 0
    for i in str(inp):
        n = n + int(i);
        print n
    

    When you are looping through something, keyword is "IN", just always think of it as a list of something. You cannot loop through a plain integer. Therefore, it is not iterable.

    0 讨论(0)
  • 2020-12-01 11:50

    Don't make it a int(), but make it a range() will solve this problem.

    inp = range(input("Enter a number: "))
    
    0 讨论(0)
提交回复
热议问题