What is the simple basic explanation of what the return statement is, how to use it in Python?
And what is the difference between it and the print
state
Best thing about return
function is you can return a value from function but you can do same with print
so whats the difference ?
Basically return
not about just returning it gives output in object form so that we can save that return value from function to any variable but we can't do with print
because its same like stdout/cout
in C Programming
.
Follow below code for better understanding
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
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?"
We are now doing our own math functions for add, subtract, multiply,
and divide
. The important thing to notice is the last line where we say return a + b
(in add
). What this does is the following:
a
and b
.a + b
. You might say this as, "I add a
and b
then return them."a + b
result to a variable.