+ 1
The indentation of print statement in for loop (python)
Why this program is right: N = int(input()) sum = 0 #your code goes here for i in range(1,N+1): sum += i print(sum) Not : N = int(input()) sum = 0 #your code goes here for i in range(1,N+1): sum += i print(sum) Why I needed to separate the print statement from the loop to get the right result? What indecat the separation of print from loops ? For and while loops extra
7 Answers
+ 3
aly nagaty ,
1. code with print() outside of the for loop:
during the loop iterations, the running *sum* is feeded with numbers that are generated from the range.
after last iteration is done, print() will output the sum of all numbers.
print is called once when the loop is terminated.
2. code with print() inside of the for loop:
this code uses print() in each loop iteration, so output will be done by showing the *subtotals*.
the last output of this code will be identical with the result of the 1. code.
+ 2
Read this, don't run it:
https://code.sololearn.com/cT5BRIbkia21/?ref=app
0
Sorry but I Don't understand
Can you explain more ?
0
the loop is calculating the sum value step by step.
so when you put the print inside the loop, it will print in every step the sum value that is calculated unless the loop ends.
so for i in range(5) will print 1 then 2 then 3 then 4 then 5. then the loop ends and ends its calculating and the sum value is complete. then you must print it . and that is why print cames sperated from the for loop to work only after the loop ends.
0
Because you have already set N as a variable in line 2 you have to call the variable or set another variable n . And debug the line 14 just like line 7
0
Remember always slip multiple input in separate line
0
Both will run but with different results. The first one is outside the loop so it prints the result of all the addition while the second one prints the addition as the numbers are being sumed