Reputation: 33
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
Upvotes: 1
Views: 36
Reputation: 59114
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
Upvotes: 4