[Python] How can I correctly calculate the sum of all numbers in a range in a while loop?

Discussão em 'Python' iniciado por Stack, Maio 16, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to calculate, using a while loop, the sum of all numbers from 20 to 100. It calculates, but I am 100% sure it is wrong.

    My code is:

    num = 20
    sum = 0
    i = 0
    while num <= 100:
    for i in range(0, num + 1):
    sum = num + 1
    num = num + 1
    continue

    print(sum)


    The result is 167. But I know it has to be 210.

    I tried various changes: for example, changed the position of num = num + 1 to after the for loop, but it does not work properly.

    Continue reading...

Compartilhe esta Página