def
In Python, the def
keyword is used to define a function. Functions allow users to group related code into blocks that can be executed repeatedly without rewriting the same lines. Using functions helps improve modularity, reduce redundancy, and increase readability.
Syntax
def function_name(parameters):
"""
Optional docstring
"""
# Function body
return result
In the syntax:
function_name
: The name of the function.parameters
(Optional): The inputs that the function can accept.return
(Optional): The value that the function returns.
Example 1: A Simple Greeting Function
In this example, the function greet()
prints the given greeting when called:
def greet():print("Hello, Codecademy!")greet()
Here is the output:
Hello, Codecademy!
Example 2: Function with Parameters
In this example, the add()
function takes two parameters and returns their sum:
def add(a, b):return a + bresult = add(5, 3)print("Sum:", result)
Here is the output:
Sum: 8
Codebyte Example: Function with Default Parameter
In this example, the power()
function uses a default parameter value (2
) for the exponent
parameter. If an argument is not provided for this parameter, the default value will be taken:
def power(base, exponent=2):return base ** exponentprint(power(4))print(power(3, 3))
Here is the output:
1627
Frequently Asked Questions
1. Can a function return multiple values?
Yes. Python functions have the ability to return multiple values as a tuple:
def get_coordinates():return 10, 20x, y = get_coordinates()
2. Can you define a function inside another function?
Yes. Python supports nested functions:
def outer():def inner():print("Inner function")inner()
3. What happens if you call a function before it’s defined?
Python will raise a NameError
. Functions must be defined before they are called in the code flow.
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