'For loop in range output start from 0 to input i have tried everything

kertoma = int(input("Kuinka monta kierrosta?:"))

tulos = int(0)

for tulos in range(1, kertoma+1):
    tulos = tulos + kertoma
    print("Kertymäksi saatiin:", int(tulos))

so my question is, if i wanna put input as 3 it should do from 0+1+2 and the out put should be 3 but instead of 3 the output is 6 and if i want to input 5 it should be 0+1+2+3+4

Thanks in advance



Solution 1:[1]

You shouldn't be adding kertoma in the loop, you should be adding the iteration variable from the range.

You need to use a different variable for the iteration than the variable you're adding to.

You don't have to write int(0), just 0. And tulos is an integer, so you don't have to write int(tulos).

The limit of the range should be kertomas, not kertomas+1, because range() doesn't include the end.

kertoma = int(input("Kuinka monta kierrosta?:"))

tulos = 0

for i in range(1, kertoma):
    tulos = tulos + i
    
print("Kertymäksi saatiin:", tulos)

Solution 2:[2]

I think you want something like this:

upper_limit = int(input("What's the upper limit? "))

total = 0

for num in range(upper_limit):
    total = total + num

print("The result is:", total)

Be aware that, for range calls, the upper limit is excluded: if you type 3 as the input, it will iterate three times (with num set to 0, 1, and 2) - having upper_limit+1 as the argument of range will also include the upper_limit itself (which is why in your case the output was 6 instead of 3).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar
Solution 2 Stefano Cianciulli