Computer Science · Ch 7 — Functions
Functions Returning Value
Functions Returning Value
A function may or may not send a value back when it is called. The return statement is what sends values out of a function.
All the example functions so far performed their calculations and displayed their results themselves — they sent nothing back to the caller. Functions that return no value are called void functions. Often, though, we need the function to hand its result back to the calling code, which then decides what to do with it. That is the job of return.
The return statement does two things:
- it returns control to the calling function (execution resumes at the point of the call), and
- it returns value(s) — or
Noneif no value is given.
A function that returns its result
The task: a user defined function calcpow() accepts a base and an exponent (both integers) as arguments and returns the value of the base raised to that exponent. Requirements — (1) base and exponent arrive as arguments, (2) compute base raised to the power exponent, (3) return the result using return, (4) the caller displays the returned value.
# Function that computes base raised to the power exponent
def calcpow(number, power): # function definition
result = 1
for i in range(1, power + 1):
result = result * number
return result # send the result back
base = int(input("Enter the value for the Base: "))
expo = int(input("Enter the value for the Exponent: "))
answer = calcpow(base, expo) # function call — returned value lands in answer
print(base, "raised to the power", expo, "is", answer)
Enter the value for the Base: 5
Enter the value for the Exponent: 4
5 raised to the power 4 is 625
Note the shape of the call: answer = calcpow(base, expo). Because the function returns a value, the call appears on the right of an assignment and the returned result is captured in a variable for later use — unlike the void functions earlier, which were called on a line of their own.