0
0
Pythonprogramming~5 mins

Function call and execution flow in Python

Choose your learning style9 modes available
Introduction

Functions help us organize code into small tasks. Calling a function runs its code step-by-step.

When you want to repeat a task many times without rewriting code.
When you want to break a big problem into smaller, easier parts.
When you want to reuse code in different places.
When you want to make your program easier to read and understand.
Syntax
Python
def function_name(parameters):
    # code block

function_name(arguments)

Define a function with def and give it a name.

Call the function by writing its name followed by parentheses.

Examples
This defines a function greet that prints a message. Calling greet() runs the print.
Python
def greet():
    print("Hello!")

greet()
This function adds two numbers and prints the result. Calling add(3, 4) prints 7.
Python
def add(a, b):
    print(a + b)

add(3, 4)
This function takes a name and prints it inside a message.
Python
def say_name(name):
    print(f"Your name is {name}.")

say_name("Anna")
Sample Program

This program shows how calling functions controls the flow. start() runs first, then calls step_one() and step_two() in order.

Python
def start():
    print("Start of program")
    step_one()
    step_two()
    print("End of program")

def step_one():
    print("Step one running")

def step_two():
    print("Step two running")

start()
OutputSuccess
Important Notes

When a function is called, the program jumps inside it and runs its code.

After the function finishes, the program goes back to where it was called.

Functions help keep code clean and easy to follow.

Summary

Functions are blocks of code you can run by calling their name.

Calling a function makes the program jump to that function's code and run it.

After the function finishes, the program continues where it left off.