+ 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)

9th Sep 2022, 5:56 AM
SAIF ALI
SAIF ALI - avatar
6 ответов
+ 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
10th Sep 2022, 3:47 PM
Lothar
Lothar - avatar
+ 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
9th Sep 2022, 6:04 AM
Lothar
Lothar - avatar
+ 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.
9th Sep 2022, 6:02 AM
Brian
Brian - avatar
+ 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!
10th Sep 2022, 12:42 PM
SAIF ALI
SAIF ALI - avatar
+ 2
Lothar Thanks mate! It's helpful
10th Sep 2022, 3:54 PM
SAIF ALI
SAIF ALI - avatar
+ 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.
10th Sep 2022, 1:37 AM
Tyler McKechnie