I'm a newbie who just starting out. I have been playing around with function and I can't understand why I get the output below from the code below:
Why doesn't it print the return value as well as text from a function in continuous lines, why does the output look like it is looping through the functions twice?
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
plus = add(1,1)
minus = subtract(1,1)
times = multiply(1,1)
print plus
print minus
print times
The output I get is:
ADDING 1 + 1
SUBTRACTING 1 - 1
MULTIPLYING 1 * 1
2
0
1
TimoSolo
7,3756 gold badges36 silver badges51 bronze badges
-
1That's the execution order of your program. First you call all the functions, then you print the results.Klaus D.– Klaus D.2018年04月19日 08:25:24 +00:00Commented Apr 19, 2018 at 8:25
1 Answer 1
Your code is written this way. First you execute all three functions. Then you print the results of all three functions.
plus = add(1,1) # ADDING 1 + 1
minus = subtract(1,1) # SUBTRACTING 1 - 1
times = multiply(1,1) # MULTIPLYING 1 * 1
print plus # 2
print minus # 0
print times # 1
If you want the results interleaved with the calculations, then interleave them.
plus = add(1,1) # ADDING 1 + 1
print plus # 2
minus = subtract(1,1) # SUBTRACTING 1 - 1
print minus # 0
times = multiply(1,1) # MULTIPLYING 1 * 1
print times # 1
answered Apr 19, 2018 at 8:25
khelwood
59.7k14 gold badges91 silver badges116 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py