► Overview
Return values allow functions to send data back to the caller. Scope determines where variables can be accessed in your code. Understanding both is crucial for writing effective functions.
► Real-World Analogy
Think of a calculator:
» Input: Numbers and operation
» Process: Perform calculation
» Return: The result
» The result goes back to whoever used the calculator
► Key Concepts
✓ return statement: Sends value back to caller
✓ Functions can return any data type
✓ return ends function execution
✓ Multiple return statements possible
✓ None returned if no return statement
✓ Local scope: Variables inside function
✓ Global scope: Variables outside function
■ Return Examples
/code
Return single value
def square(x):
return x * x
result = square(5)
print(result)
Return multiple values
def get_name():
return “John”, “Doe”
first, last = get_name()
print(f”{first} {last}”)
Early return
def check_age(age):
if age < 18:
return “Minor”
return “Adult”
print(check_age(15))
Output:
25
John Doe
Minor
► Important Points
✓ return immediately exits the function
✓ Can return multiple values as tuple
✓ Local variables exist only in function scope
✓ Global variables accessible everywhere
✓ Avoid modifying global variables in functions
✓ Use return for function output
► Remember
✓ Every function returns something (None if not specified)
✓ return stops function execution immediately
✓ Variables created in functions are local
✓ Use return to send results back to caller
✓ Global keyword needed to modify global variables
■ Practice Challenge
- Create a function that returns both quotient and remainder
- Write a function with multiple return points based on conditions
- Build a function that returns maximum of three numbers
