+ 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!?
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
+ 2
Yes, they should :) Do you understand my explanation though?
+ 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
+ 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 :)
+ 1
the answers should be switched ,, sorry
+ 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:)
+ 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
+ 1
ohhh oky thank you very much!!😁😁