Some tasks need to be performed multiple times within a program. Rather than rewrite the same code in multiple places, a function may be defined using the
def keyword. Function definitions may include parameters, providing data input to the function.
def my_function(value): return value + 1 print(my_function(2)) print(my_function(3 + 5))
Functions may return a value using the
return keyword followed by a
value. They can then be called, or invoked, elsewhere in the program. The output from the snippet above would look similar to this:
Note: Function names in Python are written in snake_case.
return keyword is used to return a value from a Python function. The value returned from a function can be assigned to a variable which can then be used in the program.
In the example below, the
check_leap_year() function returns a string that indicates if the passed parameter is a leap year or not.
def check_leap_year(year):if year % 4 == 0:return str(year) + " is a leap year."else:return str(year) + " is not a leap year."year_to_check = 2018returned_value = check_leap_year(year_to_check)print(returned_value)
The resulting output will look like this:
2018 is not a leap year.
Returning Values With
A function can also return values with the
yield keyword. Like
yield suspends the function’s execution and returns the value specified. Unlike
yield statement retains the state of the function and will resume where it left off on the next function call (i.e. execution resumes after the last
yield statement). This way, the function can produce a number of values over time.
The example below will automatically generate successive Fibonacci numbers.
# Function to produce infinite Fibonacci numbersdef fibonacci():# Generate first numbera = 1yield a# Generate second numberb = 1yield b# Infinite loopwhile True:# Return sum of a + bc = a + byield c# Function resumes loop here on next calla = bb = c# Iterate through the Fibonacci sequence until a limit is reachedfor num in fibonacci():if num > 50:breakprint(num)
This will output the following:
In Python, functions are treated as first-class objects. This means that they can be assigned to variables, stored in data structures, and passed to or returned from other functions.
Functions are considered to be “higher-order” values because they can be used as parameters or return values for other functions. One example is the built-in
filter() takes a predicate (a function that returns a boolean value) and an iterable, and returns a new iterable containing all elements of the first one that makes the predicate true.
- Anonymous Functions
- Defines a function without a name using the lambda keyword.
- Supplies data to a defined function when it is called in a program.