[Python] Why does this error occur when calculating - TypeError: The 'int' object is not...

Discussão em 'Python' iniciado por Stack, Junho 10, 2025.

  1. Stack

    Stack Membro Participativo

    The task looks like this: The input of the algorithm is a natural number N. The algorithm builds a new number R based on it as follows.

    1. The sum S1 of all odd digits of the decimal notation of the number N is calculated. If there are no odd digits, the sum of S1 is considered equal to 0.
    2. The sum S2 of all digits of the decimal notation of the number N, standing in positions with odd numbers, is calculated. The positions are numbered from left to right, starting from 1.
    3. The result R is calculated as the modulus of the difference between S1 and S2. For example, N = 4321. The sum of odd digits S1 = 3 + 1 = 4. The sum of digits in positions with odd numbers S2 = 4 + 2 = 6. The result of the algorithm is R = 6 – 4 = 2. Specify the smallest number, as a result of processing which according to this algorithm will result in the number 31.

    Here is my code:

    for a in range(100):
    s1 = sum(int(x) for x in a if int(x)%2==1)
    s2 = int(a[0])
    R = abs(s1-s2)
    if R == 31:
    print(a, R)


    This line of code moment(s1 = sum(int(x) for x in a if int(x) % 2)) returns an error:


    TypeError: 'int' object is not iterable
    ​

    What am I doing wrong or how do I write a program to find the sum of all odd digits of a number?

    Continue reading...

Compartilhe esta Página