+ 2
Can someone explain me the difference between the two!
t = 0 for i in range (1, 10): t += i print(t) t = 0 for i in range (10): t += i print(t)
6 Answers
+ 5
it would be very helpful for you if you could use a debugger so that you can step through the code.
try to use this:
https://pythontutor.com/visualize.html#mode=edit
+ 5
first sample:
range is defined with start value (1) and end value (10).
the running total (variable `t`) is build from values defined by range
after loop is terminated the total will be printed
result is 45
second sample:
range is defined with end value only, so start value is 0 by default
the running total is build from values of by range
the current value of running total is printed for each loop iteration inside the loop
result is 45
+ 4
The two loops have different starting values: first loop 1, second loop 0 (implicit). The first loop prints the result after the loop is done. The second loop prints every change while the loop is running.
+ 2
Lothar This mean when a statement is inside loop it also runs till the loop ends and if it is outside the loop I runs only once right!
+ 2
Lothar Thanks mate! It's helpful
+ 1
Just to add on to the other answers, the reason why the first block of code prints t only at the end and the second block prints it for every value in the range is because of the indentation. It might be obvious, but sharing just in case.