Back to Python Notes
Topic #201

Functions in Python

By the end of this lesson, you will be able to define reusable functions in Python using def, pass data via parameters, return results, and set default values for optional arguments.

What it is

A function is a named block of code that performs a specific task. It allows you to encapsulate logic so it can be reused without rewriting the same lines. The mental model is simple: think of a function as a machine where you input raw materials (parameters), process them internally, and output a finished product (return value).

Key terms include:

  • Definition: Creating the function using the def keyword.
  • Call: Executing the function by using its name followed by parentheses.
  • Parameter: A variable listed inside the parentheses in the function definition.
  • Argument: The actual value sent to the function when it is called.

Why it matters

  • Reusability: Write code once and use it multiple times across your program.
  • Maintainability: Fix bugs or update logic in one place rather than searching through scattered code.
  • Readability: Break complex problems into smaller, named steps that describe intent clearly.
  • Modularity: Isolate functionality, making it easier to test individual components independently.

Syntax or steps

The basic structure requires the def keyword, a unique name, parentheses containing parameters, a colon, and an indented body.

  1. Start with def.
  2. Add the function name (use lowercase with underscores).
  3. Include parameters inside parentheses.
  4. End the line with a colon :.
  5. Indent the code block that follows.
  6. Use return to send a result back to the caller.

Example

def calculate_area(width, height=10):
    """Calculate the area of a rectangle."""
    area = width * height
    return area

# Call with two arguments
result1 = calculate_area(5, 8)
print(f"Area with explicit height: {result1}")

# Call with one argument (uses default height=10)
result2 = calculate_area(5)
print(f"Area with default height: {result2}")

Explanation:

  • def calculate_area... defines the function.
  • width is a required parameter; height=10 is an optional parameter with a default value.
  • The body calculates the product and stores it in area.
  • return area sends the calculated value back to the variable calling the function.
  • The first call passes both values. The second call omits height, so Python automatically uses 10.

Common mistakes

  • Forgetting to return: If you omit return, the function returns None. Ensure you explicitly return the result if you need to use it later.
  • Mutable default arguments: Never use lists or dictionaries as default values (e.g., def func(items=[])). This causes unexpected behavior because the list persists between calls. Use None instead and initialize inside the function.
  • Indentation errors: Python relies on indentation. All code inside the function must be indented consistently (usually 4 spaces).
  • Calling before defining: You cannot call a function before the interpreter has read its definition.

When to use it

Functions are essential for any logic used more than once or any task that benefits from isolation. Compare them with inline code blocks:

Feature Function Inline Code
Reusability High Low
Testing Easy (unit tests) Hard
Overhead Slight performance cost None
Best For Complex or repeated logic Simple, one-off calculations

Practice

Guided Exercise: Create a function named greet_user that takes a name parameter and prints "Hello, [name]!". Call it with your own name.

Challenge: Modify calculate_area to accept a third parameter shape with a default value of "rectangle". If shape is "square", ignore the height and square the width. Hint: Use an if statement inside the function.

Quick check

Question: What happens if you call a function that does not have a return statement?

Answer: The function executes its code but returns None implicitly.

Summary

Functions are the building blocks of organized Python code, allowing you to bundle logic into reusable units. By mastering parameters, return values, and defaults, you create flexible tools that make your programs cleaner, easier to debug, and scalable.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Functions in Python – FAQs

Quick answers about learning Functions in Python in Python.

This free note from Coding Now Tech Institute explains Functions in Python in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Functions in Python, is 100% free with no signup required.
With focused practice, most students grasp Functions in Python in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now