0

How did this happened?

x = 0 for I in [5,4,3,2,1]: x = x + 1 print(x) answer is 5 can any one explain how did this happen. Thanks in advance.

2nd Jun 2018, 1:03 PM
Aman Rai
Aman Rai - avatar
4 ответов
+ 4
There are 5 items in the list so x = x + 1 is running five times.
2nd Jun 2018, 1:10 PM
Paul
Paul - avatar
+ 3
you made 5 cycles in the for-loop. therefore x = 1 + 1 + 1 + 1 + 1 = 5
2nd Jun 2018, 1:09 PM
Jiří Bočan
+ 2
You also can write: x=0 for i in [5,4,3,2,1]: x += i print(x) #output 15
2nd Jun 2018, 3:50 PM
李立威