Defining and Calling Functions in Python: Syntax, Examples and Execution

Introduction: Defining and Calling Functions in Python

Defining and calling functions in Python starts with using the def keyword and a function name.

  • When you define a function, you specify the instructions that belong to it.
  • When you call the function, Python executes those instructions.

For example, the following code defines a function named greet() and then calls it:

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

greet()

# Output:
Hello, Python!

Explanation: This tutorial explains how function calls work, how defining a function differs from calling one, how Python executes function calls, and common mistakes to avoid.

Calling a Function

A function is called by writing its name followed by parentheses. This tells Python to execute the instructions inside the function.

Function Call Syntax and Execution Flow

The following example shows how a function call starts the execution of the function body:

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

print("The program starts here")
greet()
print("Function execution is complete, and control returns to the statement after the function call.")


# Output:
The program starts here
Hello, Python!
Function execution is complete, and control returns to the statement after the function call.

Explanation: When Python reaches a function call, it runs the statements inside the function. After the function finishes, Python continues with the next statement after the function call.

Here’s the complete execution flow when a function greet() is called:

Execution Flow:

The execution proceeds in this order:

  1. print("The program starts here") executes first.
    Output: The program starts here.
  2. Execution reaches the function call greet().
  3. The function body executes.
    print("Hello, Python!") outputs: Hello, Python!.
  4. Execution then continues with the statement after greet().
    print("Function execution is complete, and control returns to the statement after the function call.") outputs: Function execution is complete, and control returns to the statement after the function call..

Note: The parentheses are required to call the function. Writing only greet refers to the function itself; it does not call the function.

Flow Chart: The function call moves through the program in this order

┌──────────────────────────────────────────────┐
│ Program starts                               │
│ print("The program starts here")             │
└──────────────────────┬───────────────────────┘
                       │
                       ▼
┌──────────────────────────────────────────────┐
│ Function call                                │
│ greet()                                      │
└──────────────────────┬───────────────────────┘
                       │
                       ▼
┌──────────────────────────────────────────────┐
│ Function body executes                       │
│ print("Hello, Python!")                      │
└──────────────────────┬───────────────────────┘
                       │
                       ▼
┌──────────────────────────────────────────────┐
│ Function finishes                            │
│ Control returns to the statement after       │
│ greet()                                      │
└──────────────────────┬───────────────────────┘
                       │
                       ▼
┌──────────────────────────────────────────────┐
│ Next statement executes                      │
│ print("Function execution is complete...")   │
└──────────────────────────────────────────────┘

Calling a Function Multiple Times

A function can be called more than once. Each call runs the function body again.

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

greet()
greet()
greet()

This produces:

Hello, Python!
Hello, Python!
Hello, Python!

Explanation: Here, the function is defined once, but the program calls it three times. Each call executes the function body once.

Definition vs Function Call

The difference between defining and calling functions in Python is simple: the function definition creates the function, while the function call runs the instructions inside it.

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

greet()

Explanation: The first part is the function definition. Python sees def greet(): and treats the indented print() statement as part of the function named greet. The code inside the function does not run at this point.

The second part is the function call. Writing greet() tells Python to use the function that was defined earlier.

Function Definition Function Call
Uses the def keyword Uses the function name followed by parentheses
Creates the function and defines its instructions Runs the instructions in the function
Normally written once Can be written whenever the function needs to run

A simple way to remember the difference is: define the function first, then call it when you want its code to run.

Indentation in Function Definitions

Python uses indentation to define the statements that belong to a function. The statements inside a function body must be indented under the def statement.

In this section, you will learn:

A) Indentation Inside a Function

All statements that belong to a function must be indented under the function definition.

Example 1: Indented Statements

def greet():
    print("Hello, Python!")
    print("Welcome!")

Explanation: Both print() statements are indented under the function definition, so Python treats them as part of the greet() function.

Example 2: Statement Outside the Function

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

print("Outside the function")

# Output:
Outside the function

Explanation: The first print() statement is indented, so it belongs to greet(). The second print() statement is not indented, so it is outside the function.

Remember that defining a function does not execute its body. The statements inside greet() run only when the function is called.

↑ Move to Section Top

B) IndentationError in Function Definitions

A function must have an indented body. If the required indentation is missing, Python raises an IndentationError.

Example 3: Incorrect Indentation

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

greet()

# Error:
IndentationError: expected an indented block after function definition

Explanation: The print() statement is intended to be part of the greet() function, but it is not indented. Python therefore raises an IndentationError.

Example 4: Correct Indentation

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

greet()

# Output:
Hello, Python!

Explanation: The print() statement is correctly indented under the function definition, so Python recognizes it as part of the function body.

↑ Move to Section Top

C) Indentation in Nested Blocks

Indentation can also create nested blocks inside a function. A statement with an additional level of indentation belongs to the inner block.

Example 5: Nested if Block

def greet():
    print("Hello!")
    if True:
        print("Welcome!")

greet()

# Output:
Hello!
Welcome!

Explanation: The if statement is indented under the function definition, so it belongs to the function. The print("Welcome!") statement has an additional level of indentation, so it belongs to the if block.

In this way, indentation shows the structure of the code: the first indentation level belongs to the function, while the second level belongs to the nested if block.

↑ Move to Section Top

Common Mistakes: Defining and Calling Functions in Python

Defining and calling functions in Python is simple, but small syntax mistakes can prevent them from working correctly.

Here are the common mistakes covered in this section:

To understand these mistakes, let’s look at each one and see how to fix it.

1. Forgetting the def Keyword

Rule: The def keyword is required when defining a function.

Incorrect:

greet():
    print("Hello, Python!")

greet()


# Error:
SyntaxError: invalid syntax

Explanation: The function definition is missing def.

Correct:

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

greet()


# Output:
Hello, Python!

Explanation: Here, def correctly starts the function definition.

↑ Move to Section Top

2. Forgetting the Colon

Rule: A function definition must end with a colon.

Incorrect:

def greet()
    print("Hello, Python!")

greet()


# Error:
SyntaxError: expected ':'

Explanation: The colon is missing after the closing parenthesis.

Correct:

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

greet()


# Output:
Hello, Python!

Explanation: Here, the colon correctly marks the beginning of the function body.

↑ Move to Section Top

3. Incorrect Indentation

Rule: Statements inside a function must be indented under the function definition.

Incorrect:

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

greet()


# Error:
IndentationError

Explanation: The print() statement is not indented.

Correct:

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

greet()


# Output:
Hello, Python!

Explanation: Here, the print() statement is correctly indented as part of the function body.

↑ Move to Section Top

4. Calling a Function Before Defining It

Rule: Python must execute the function definition before it reaches the function call.

Incorrect:

greet()

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


# Error:
NameError: name 'greet' is not defined

Explanation: The function is called before Python has executed its definition.

Correct:

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

greet()


# Output:
Hello, Python!

Explanation: Here, the function is defined before greet() is called.

↑ Move to Section Top

5. Forgetting Parentheses in a Function Call

Rule: Parentheses are required to call a function. Writing only the function name refers to the function but does not run it.

Incorrect:

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

greet


# Output:

Explanation: No output is produced because greet only refers to the function.

Correct:

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

greet()


# Output:
Hello, Python!

Explanation: Here, greet() correctly calls the function and runs its code.

↑ Move to Section Top

Examples: Defining and Calling Functions in Python

These examples show different ways to define and call functions in simple Python programs.

  1. Simple Function
  2. Calling a Function Multiple Times
  3. Function with Multiple Statements
  4. Using a Function with Other Statements

1. Simple Function

A function can group a small set of instructions under one name.

def welcome():
    print("Welcome to Python!")

welcome()


# Output:
Welcome to Python!

Explanation: The function is defined with def welcome(): and called with welcome(). The print() statement runs when the function is called.

↑ Move to Section Top

2. Calling a Function Multiple Times

Python allows us to call the same function more than once.

def show_message():
    print("Keep learning Python!")

show_message()
show_message()


# Output:
Keep learning Python!
Keep learning Python!

Explanation: The same function can be called multiple times, and each call executes its function body once.

↑ Move to Section Top

3. Function with Multiple Statements

A function can contain more than one statement. The statements run in order when the function is called.

def show_message():
    print("Hello!")
    print("Welcome to Python!")

show_message()


# Output:
Hello!
Welcome to Python!

Explanation: Both print() statements belong to the function because they are indented at the same level.

↑ Move to Section Top

4. Using a Function with Other Statements

A function call can appear between other statements in a program.

def show_total():
    print("Total: ₹500")

print("Order Summary")
show_total()
print("Thank you for your order!")


# Output:
Order Summary
Total: ₹500
Thank you for your order!

Explanation: The function call runs between two other statements, and execution continues with the next statement after the function finishes.

↑ Move to Section Top

Key Takeaways: Defining and Calling Functions in Python

Here are the main points to remember about defining and calling functions in Python:

  • Use def and a function name to define a function.
  • Call the function to run the code inside it.
  • Call the same function as many times as needed.
  • Indent the statements inside a function properly.
  • Define the function before Python reaches its call.
  • After a function runs, Python continues with the next statement.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top