CS Pathfinder Logo CS Pathfinder

Unit 3 · Functions

Defining and Calling Functions

Learn how to create your own functions using the def keyword and how to invoke them whenever needed. Master function naming rules, indentation, docstrings, and the complete execution flow from definition to call.

Introduction

In the previous chapter, you learned why functions are important and how they reduce code duplication. Now it is time to write your own functions. In Python, a function is created using the def keyword followed by a name, parentheses, and a colon. The body of the function is indented below the header.

Defining a function does not execute it immediately. The code inside the function only runs when the function is called by writing its name followed by parentheses. This separation of definition and execution is a fundamental concept in Python programming.

This chapter walks you through every detail—from naming rules and indentation to docstrings and execution flow—so you can define and call functions with confidence.

University Definition

Defining a function means writing a named block of code that performs a specific task. The function definition consists of the def keyword, a function name, optional parameters, and an indented body. Calling a function means executing the defined block by referencing its name followed by parentheses.

Syntax of a Function

Every user-defined function in Python follows this general syntax:

def function_name(parameters):
    """Docstring describing the function."""
    # function body
    # one or more statements

Breakdown of the syntax:

  • def — The keyword that tells Python you are defining a function.
  • function_name — A meaningful name you choose (follows variable naming rules).
  • (parameters) — Optional list of variables that receive input values.
  • : — A colon that marks the end of the function header.
  • Docstring — An optional string that documents what the function does.
  • Indented body — The statements that form the function's logic.

Example 1 — Simplest Function

Let us define and call the most basic function possible:

def greet():
    print("Hello, welcome to Python!")

greet()
greet()
Output:
Hello, welcome to Python!
Hello, welcome to Python!

Step-by-step explanation:

  1. Line 1: def greet(): defines a function named greet. Nothing is executed yet.
  2. Line 2: The indented print() statement becomes the body of the function.
  3. Line 4: greet() calls the function. Now Python executes the body.
  4. Line 5: The second call repeats the execution.

Example 2 — Function with Parameters

def greet_person(name):
    print("Hello, " + name + "!")

greet_person("Alice")
greet_person("Bob")
Output:
Hello, Alice!
Hello, Bob!

Here, name is a parameter. When you call greet_person("Alice"), the string "Alice" is an argument that gets assigned to the parameter name inside the function.

Example 3 — Multiple Parameters

def add(a, b):
    result = a + b
    print("Sum =", result)

add(10, 20)
add(5, 7)
Output:
Sum = 30
Sum = 12

You can define as many parameters as you need, separated by commas.

Real-Life Analogy

Think of a microwave. The manufacturer writes the instruction manual (function definition) once. Every user reads the manual and presses the start button (function call) whenever they need to heat food. The manual does not cook food by itself—it only works when someone follows (calls) the instructions.

Similarly, defining a function only creates the instructions. Calling the function makes Python actually execute those instructions.

Function Naming Rules

Naming Conventions

Must start with a letter or underscore (_).

Can contain letters, digits, and underscores.

Cannot start with a digit.

Cannot use Python reserved keywords (if, for, while, etc.).

Case-sensitive: Greet and greet are different.

Use lowercase with underscores for readability (calculate_average).

Docstrings — Documenting Your Function

A docstring is a string literal placed as the first statement inside a function. It describes what the function does. You can access it using function_name.__doc__.

def multiply(a, b):
    """Return the product of two numbers."""
    return a * b

print(multiply.__doc__)
print(multiply(3, 4))
Output:
Return the product of two numbers.
12

Docstrings are considered best practice. They help other developers (and your future self) understand the function without reading its code.

Defining vs Calling a Function

Defining a Function

  • Uses the def keyword.
  • Creates the function but does not execute it.
  • Written once and reused many times.
  • Example: def greet():

Calling a Function

  • Uses the function name followed by ().
  • Executes the code inside the function body.
  • Can be done as many times as needed.
  • Example: greet()

Execution Flow of a Function

Consider the following code:

print("Step 1")

def my_func():
    print("Inside function")

print("Step 2")
my_func()
print("Step 3")
Output:
Step 1
Step 2
Inside function
Step 3

Explanation:

  1. Python executes top-level statements in order.
  2. When it reaches def my_func():, it defines the function but does not run the body.
  3. print("Step 2") executes next.
  4. my_func() calls the function, so the body runs: print("Inside function").
  5. After the function finishes, execution continues to print("Step 3").

Functions with No Parameters and No Return

A function does not need parameters or a return value. It can simply perform an action:

def display_menu():
    print("===== MENU =====")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")
    print("=================")

display_menu()
Output:
===== MENU =====
1. Add
2. Subtract
3. Multiply
4. Divide
=================

This is useful for organizing output into logical blocks and avoiding repetition.

Common Mistakes

Mistake 1 — Forgetting the Colon

def greet()    # SyntaxError: expected ':'
    print("Hello")

Always put a colon after the function header.

Mistake 2 — Wrong Indentation

def greet():
print("Hello")    # IndentationError

The function body must be indented (4 spaces is standard).

Mistake 3 — Calling Before Defining

greet()         # NameError: name 'greet' is not defined

def greet():
    print("Hello")

Always define the function before you call it.

University Exam Tip

University exams often ask you to:

  • Define a function and explain each part of its syntax.
  • Distinguish between defining and calling a function.
  • Trace the output of a code snippet with function definitions and calls.
  • Explain why the function body must be indented.

Practice Questions

Q1. Write a function print_square(n) that prints the square of a number.

def print_square(n):
    print(n * n)

print_square(5)
# Output: 25

Q2. What will be the output of the following code?

def display():
    print("A")

def main():
    display()
    display()

main()
display()
Answer: A, A, A

Q3. Write a function is_even(num) that prints whether a number is even or odd.

def is_even(num):
    if num % 2 == 0:
        print(num, "is even")
    else:
        print(num, "is odd")

is_even(4)   # 4 is even
is_even(7)   # 7 is odd

Q4. What is the difference between a function definition and a function call?

Answer: A function definition uses the def keyword to create the function. A function call executes the function by writing its name followed by parentheses.

Q5. Write a function display_info(name, age) that prints a person's name and age.

def display_info(name, age):
    print("Name:", name)
    print("Age:", age)

display_info("Alice", 21)

Summary

  • Use the def keyword to define a function.
  • The function body must be indented.
  • Defining a function does not execute it.
  • Write the function name with parentheses to call it.
  • Function names follow the same rules as variable names.
  • Docstrings document the purpose of the function.
  • Execution flows sequentially, skipping definitions until called.

Python Programming Handwritten Notes

Master Python Programming with Easy Handwritten Notes – Perfect for Interviews, Placements, GATE & Exams.