+ 4

Why do they give different answers?

def add_numbers(*args): total = 20 for a in args: total += a print(total) add_numbers(29) add_numbers(1, 3, 5, 8) def add_numbers(*args): total = 20 for a in args: total += a print(total) add_numbers(29) add_numbers(1, 3, 5, 8) answers for the first one is: 49 21 24 29 37 answers for the second one is: 49 37 I know how the answers came to be in both,but why are they different if the only difference is where the pieces of codes "print(total)" is aligned!?

15th Mar 2018, 12:01 PM
Leonardo
Leonardo - avatar
8 Réponses
+ 2
In the first code print is in the for loop so it prints everytime it adds a number to sum In the second code print is outside the for loop so it only prints when it has finished doing all the sums
15th Mar 2018, 12:16 PM
cyk
cyk - avatar
+ 2
Yes, they should :) Do you understand my explanation though?
15th Mar 2018, 3:34 PM
cyk
cyk - avatar
+ 2
You have to be very careful with the indentation. for a in args: total += a print (total) This print is inside the foor loop for a in args: total += a print (total) This print is outside the for loop
15th Mar 2018, 3:41 PM
cyk
cyk - avatar
+ 2
You can place it where you want depending on what you want to print. If you wanted to print total every time you will place print inside the loop. But if you only want the final total you will place print outside the loop :)
15th Mar 2018, 3:47 PM
cyk
cyk - avatar
+ 1
the answers should be switched ,, sorry
15th Mar 2018, 3:32 PM
Leonardo
Leonardo - avatar
+ 1
I'm just confused ,,, by which print is inside the loop and which one is outside? but futhermore I do understand what you mean:)
15th Mar 2018, 3:38 PM
Leonardo
Leonardo - avatar
+ 1
yea i know ,it's this app where it doesn't automatically go to the correct position after pressing enter ,, but when ypu use something like pycharm where it automatically moves by itself. and MUST the print always be outside the for loop (is that the norm) or can you place it where you like ,, depending on how you want your answer
15th Mar 2018, 3:44 PM
Leonardo
Leonardo - avatar
+ 1
ohhh oky thank you very much!!😁😁
15th Mar 2018, 3:52 PM
Leonardo
Leonardo - avatar