Python def

Sriparno08's avatar
Published Jul 2, 2025
Contribute to Docs

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.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

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 + b
result = 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 ** exponent
print(power(4))
print(power(3, 3))

Here is the output:

16
27

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, 20
x, 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.

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours