+ 2

Need help

a=0 for i in range (0,10): if i==0: a=13 else: a-=1 print(a) output: 4 WHY???

27th Dec 2017, 9:10 PM
Джуди Вуди
Джуди Вуди - avatar
5 Answers
+ 12
loop runs 10 times, on every loop it subtracts 1 except the first one in which "a" gets the value 13 so... 1 loop for : a=13 9 loops : a = a-1 13-9(loops)=4
27th Dec 2017, 9:20 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 5
range(0,10) goes from 0 to 9. The 1st time through the loop i = 0 so 'a' gets set to = 13 then for the next 9 times it goes into the 'else'. Each time through the else statement 'a' is reduced by 1 until the final time in the for loop where it equals 4: i = 0, a = 13 i = 1, a = 12 i = 2, a = 11 etc i = 9, a = 4
27th Dec 2017, 9:17 PM
Duncan
Duncan - avatar
+ 3
If I want to understand a Code like this, I let the program return the current values after every Loop: a=0 for i in range (0,10): if i==0: a=13 else: a-=1 print(a) # this is the additional line print(a) output: 4 WHY???
27th Dec 2017, 9:51 PM
Sebastian Keßler
Sebastian Keßler - avatar
+ 2
@H Chiang - the print is outside the for loop in the original question and Sebastian added an extra print inside the loop as per his comment to demonstrate what the value was for 'a' at each pass through the loop. Also you've included curly brackets {} which Python doesn't use. Like you said it uses indentation.
28th Dec 2017, 1:21 AM
Duncan
Duncan - avatar
- 1
Everybody is correct but here is my 2 cents. Python is very strict on indents to determine if code is in the same block. Hence your program should be similar to the following: a=0 for i in range (0,10):{ if i==0: a=13 else: a-=1 }//end of for loop print(a) Because print is outside the loop, nothing is printed until after the loop finishes. Hence the output: 4
28th Dec 2017, 1:10 AM
H Chiang