How to Return Value from Function in Python: Simple Guide
In Python, you use the
return statement inside a function to send a value back to where the function was called. The value after return is the output you get when you run the function.Syntax
The basic syntax to return a value from a function in Python is:
def: starts the function definition.function_name(): the name of the function.return value: sends the value back to the caller.
python
def function_name(): # do something return value
Example
This example shows a function that adds two numbers and returns the result. The returned value is then printed.
python
def add_numbers(a, b): result = a + b return result sum_value = add_numbers(3, 5) print(sum_value)
Output
8
Common Pitfalls
One common mistake is forgetting the return statement, which makes the function return None by default. Another is placing code after return, which will never run because return ends the function.
python
def wrong_function(): x = 10 # Missing return statement print(wrong_function()) # Output: None def unreachable_code(): return 5 print("This will never print") # This line is ignored
Output
None
Quick Reference
Remember these tips when returning values from functions:
- Use
returnto send back any value. - A function without
returnreturnsNone. - Code after
returnis not executed. - You can return any data type: numbers, strings, lists, or even other functions.
Key Takeaways
Use the
return statement to send a value back from a function.Without
return, a function returns None by default.Code after
return is never executed.You can return any type of data from a function.
Always place
return where you want the function to stop and give back a result.