Returning Values from Functions #
Another important feature of creating functions is the ability to return values or return the result of the function. The value returned can be assigned to a variable or used for other purposes. We can return a value using the return keyword followed by the value we want to return, as shown in the example below:
This function takes a year in AD as an argument and returns the corresponding year in the Buddhist era (BE) when called.
def year_ac_to_be(year):
return year + 543
year_in_ac = 2000
year_in_be = year_ac_to_be(year_in_ac)
print(year_in_be) # Output: 2543
The keyword return is not necessary for a function. When a function does not return anything, the value None is returned. For example:
def do_something():
print("Do this")
result = do_something()
print(result) # Output: None
When a function returns a value, it immediately stops executing the remaining parts of the function. For example, in the code below, the function will return True when called and the print function that follows will not be executed. Try copying the code to an editor and running the code to see the result.
def print_hello_world():
return True
print("Hello World")
result = print_hello_world()
print(result)
Output:
True
Exercise #
Create a function that accepts arguments and returns a values.
Tests #
- Create a function
add_numbers - Function
add_numbersshould accept 2 arguments add_numbers(5, 5)shouldreturn10add_numbers(10, 10)shouldreturn20
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules