+ 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

18th Apr 2022, 4:01 AM
aly nagaty
7 Respuestas
+ 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.
18th Apr 2022, 9:54 AM
Lothar
Lothar - avatar
18th Apr 2022, 10:08 AM
HonFu
HonFu - avatar
0
Sorry but I Don't understand Can you explain more ?
18th Apr 2022, 9:50 AM
aly nagaty
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.
19th Apr 2022, 12:13 AM
Mohamed Ayaou
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
19th Apr 2022, 7:17 AM
Bean Hong
0
Remember always slip multiple input in separate line
19th Apr 2022, 7:30 AM
Bean Hong
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
19th Apr 2022, 3:40 PM
okonkwo calistus
okonkwo calistus - avatar