Functions
A function in Python is a block of code that allows tasks to be performed multiple times within a program without having to be rewritten. It helps in reducing code duplication, improving readability and organization, dividing a program into smaller chunks, and facilitate debugging and testing.
Defining a Function
Python functions are defined with the def
keyword followed by the name of the function and parentheses:
# Define a functiondef hello():print("Hello, world!")# Call the functionhello()
In this example, the hello()
function prints the given message to the console.
Here is the output:
Hello, world!
Defining a Function with Parameters
Python functions can be defined with parameters, which help in passing data to the function:
# Define a functiondef hello(name):print(f"Hello, {name}!")# Call the functionhello("Robin")
In this example, a name is passed to the function as an argument, which is stored in the name
parameter (variable).
Here is the output:
Hello, Robin!
Note: Function names in Python are written in snake_case.
Returning Values from a Function
In Python, a value can be returned from a function in two ways:
- Using the
return
keyword - Using the
yield
keyword
Returning Values Using return
The return
keyword is used to return a value from a Python function. The value returned can then be stored in a variable and used in the program.
In this example, the check_leap_year()
function returns a string that indicates if the given year is a leap year or not:
# Define a functiondef check_leap_year(year):if year % 4 == 0:return str(year) + " is a leap year."else:return str(year) + " is not a leap year."# Store the year to check in a variableyear_to_check = 2018# Call the functionreturned_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 Using yield
A function can also return values with the yield
keyword. Like return
, yield
suspends the function’s execution and returns the value specified. Unlike return
, the 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.
Functions using yield
rather than return
are known as generator functions. Such a function can be used as an iterator.
This example 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)
Here is the output:
112358132134
Python Library Functions
Python library functions are built-in functions that are always available for use without needing to define them explicitly. These functions are a part of the Python standard library and help perform common tasks like mathematical operations, type conversions, string manipulations, and more.
Some examples for Python library functions are:
Example: Using the len()
Function
The len()
function is a commonly used library function in Python that returns the total number of elements in an object like a string, list, tuple, etc.
# Define a listmy_list = [10, 20, 30, 40]# Return the number of items in the listprint(len(my_list))
Here is the output:
4
Higher-Order Functions
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.
Example: Using the filter()
Function
The built-in filter()
function in Python is used to filter elements from an iterable (like lists, tuples, or sets) that satisfy a specific condition:
# Function that returns True if n is a perfect square, and False otherwisedef is_perfect_square(n):return (n ** 0.5).is_integer()# Store the numbers to check in a variablenumbers = [3, 4, 37, 9, 7, 32, 25, 81, 79, 100]# Call the functionperfect_squares = filter(is_perfect_square, numbers)print(list(perfect_squares))
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
.
Here is the output:
[4, 9, 25, 81, 100]
Codebyte Example: Calculate the Area of a Rectangle
This codebyte example defines a function to calculate the area of a rectangle with the help of its length and width:
Frequently Asked Questions
1. What’s the difference between a parameter and an argument in a Python function?
- A parameter is a variable used in the function definition.
- An argument is the value passed to the function when it’s called.
2. What happens if you call a function before defining it?
Python will raise a NameError
because the function must be defined before it is called.
3. What is a default parameter in a Python function?
A default parameter in a Python function is a value that is used if no argument is provided:
def hello(name="Guest"):print(f"Hello, {name}!")
Here, the given value will be used for the name
parameter (variable) if no argument is passed to the function.
Functions
- Anonymous Functions
- Defines a function without a name using the lambda keyword.
- Arguments/Parameters
- Supplies data to a defined function when it is called in a program.
All contributors
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours