We can pass values into a function with arguments. You can use a return statement to send a value back out of a function.
The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to answer below):
def plusThree(num):
return num + 3
answer = plusThree(5)
answer has the value 8.
plusThree takes an argument for num and returns a value equal to num + 3.
No return statement:
In the case that the function doesn't have a return statement, when you call it, the function processes the inner code but the returned value is None:
sum = 0
def addToSum(num):
sum += num
returned = addToSum(3)
print(sum) # Output: 3
print(returned) # Output: None
addSum is a function without a return statement. The function will change the global sum variable but the returned value of the function is None.
Assignment
Follow the Coding Tutorial and let's write some functions.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
