+ 1

why doesn't this code iterate through all the n in range?

N = int (input()) for n in range (N+1): n += n print (n) my thought is that it takes the input and let's say it is 5 and goes for all in range 6 so 0 - 5 and goes through them: 0 += 0 0 += 1 1 += 2 3 += 3 6 += 4 10 += 5 leaving n = 15 at the end but it doesn't do that

20th Aug 2021, 4:49 PM
Cynic
Cynic - avatar
3 Antworten
+ 5
You need a sum variable N = int (input()) sumVar = 0 for n in range (N+1): sumVar += n print (sumVar) Shorter solution N = int(input()) print (sum(range(1,N+1)))
20th Aug 2021, 4:52 PM
David García Prados
+ 1
thank you
20th Aug 2021, 4:57 PM
Cynic
Cynic - avatar
+ 1
What's happening is: 1st iteration n = 0 (for n = 0..5) n = 0 + 0 (n+=0) 2nd n = 1 n = 1 + 1 3rd n = 2 n = 2 + 2 . . . 6th n = 5 n = 5 + 5
20th Aug 2021, 10:42 PM
Angelo
Angelo - avatar