Nearby lessons

69 of 159

Python - Functions

📌 What You Will Learn
  • Understand what a function is and why it promotes code reusability
  • Define and call functions using the def keyword
  • Distinguish between built-in functions and user-defined functions
  • Understand global and local variables and their scope
  • Use the global keyword to modify global variables inside a function
  • Use the globals() function to access and modify global variables

Introduction to Functions

While writing programs, sometimes we need to write the same group of statements again and again.

Writing the same code repeatedly is not a good programming practice because it increases the size of the program and makes maintenance difficult.

Instead of rewriting the same statements multiple times, we can group them together into a single unit and use that unit whenever required.

This single unit is called a Function.

A function allows us to write the code once and execute it many times by simply calling the function.

Definition of Function

A Function is a group of related statements that performs a specific task.

Once a function is created, it can be called whenever required without rewriting the same code.

Real-Life Example

Suppose a school management system needs to print the following message many times:

Hello Students
Welcome to Python Class

Instead of writing these statements repeatedly, we can place them inside a function and call that function whenever needed.

Advantages of Functions

According to the tutorial, the main advantage of functions is Code Reusability.

Functions also provide several additional benefits.

  • Code Reusability.
  • Reduces duplicate code.
  • Improves readability.
  • Makes programs easier to maintain.
  • Reduces program size.
  • Makes debugging easier.
  • Improves modular programming.

Code Reusability

Code Reusability means writing the code once and using it many times.

Instead of copying the same statements into different parts of the program, we simply call the function.

This saves both time and effort.

Types of Functions

Python supports two types of functions.

  1. Built-in Functions
  2. User Defined Functions

1. Built-in Functions

Functions that are already available in Python are called Built-in Functions or Predefined Functions.

These functions are automatically available after installing Python.

We do not need to write their implementation.

Common Built-in Functions

Some common built-in functions are:

  • id()
  • type()
  • input()
  • eval()
  • len()
  • print()
  • sum()
  • max()
  • min()

Example

🐍Code Cell
1print(len("Python"))
2 
3print(type(100))
4 
5print(max(10, 20, 30))
Output
6

30

2. User Defined Functions

Functions created by the programmer according to business requirements are called User Defined Functions.

These functions are written using the def keyword.

Syntax of User Defined Function

🐍Code Cell
1def function_name(parameters):
2 """Doc String"""
3 
4 statements
5 
6 return value
Output
No output captured.

Syntax Explanation

Part Description
def Keyword used to define a function.
function_name Name of the function.
parameters Input values accepted by the function.
Doc String Description of the function.
statements Task performed by the function.
return Returns the result to the caller.

The def Keyword

The def keyword is used to create a User Defined Function.

Every function definition begins with the def keyword.

Syntax

🐍Code Cell
1def function_name():
2 statements
Output
No output captured.

First Function Program

🐍Code Cell
1def wish():
2 print("Hello Good Morning")
3 
4wish()
5 
6wish()
7 
8wish()
Output
Hello Good Morning
Hello Good Morning
Hello Good Morning

Understanding the Program

def wish():

Defines a function named wish().

print("Hello Good Morning")

This statement is executed whenever the function is called.

wish()

Calls the function.

Since the function is called three times, the message is printed three times.

Calling a Function

A function is executed only when it is called.

Simply defining a function does not execute it.

Syntax

🐍Code Cell
1function_name()
Output
No output captured.

Example

🐍Code Cell
1def message():
2 print("Welcome")
3 
4message()
Output
Welcome

Important Point

Merely defining a function does not execute it.

The function body is executed only when the function is called.

Difference Between Defining and Calling a Function

Defining Function Calling Function
Creates the function. Executes the function.
Uses def. Uses the function name followed by parentheses.
Executed only once. Can be executed any number of times.

Introduction to Variables in Functions

Variables are used to store data in a program.

Depending on where a variable is declared, Python classifies variables into different types.

Python supports two types of variables:

  • Global Variables
  • Local Variables

Understanding the scope of variables is very important because it determines where a variable can be accessed and modified.

Function vs Module vs Library

Before learning Global and Local Variables, it is important to understand three related terms.

Term Description
Function A group of statements written together to perform a specific task.
Module A file that contains one or more functions.
Library A collection of multiple related modules.

Global Variables

The variables declared outside of every function are called Global Variables.

Global variables belong to the entire module.

Every function inside the same module can access global variables unless a local variable with the same name exists.

Characteristics of Global Variables

  • Declared outside all functions.
  • Accessible throughout the module.
  • Can be shared by multiple functions.
  • Remain available until the program finishes.

Program: Accessing a Global Variable

🐍Code Cell
1a = 10 # Global Variable
2 
3def f1():
4 print(a)
5 
6def f2():
7 print(a)
8 
9f1()
10f2()
Output
10
10

Understanding the Program

The variable a is declared outside every function.

Therefore, it becomes a Global Variable.

Both f1() and f2() can access the same variable.

No separate copy of the variable is created for each function.

Scope of Global Variables

Declared Outside Function? Accessible Inside Function? Accessible by Multiple Functions?
Yes Yes Yes

Local Variables

The variables declared inside a function are called Local Variables.

A local variable exists only while the function is executing.

After the function completes, the local variable is destroyed.

It cannot be accessed from outside the function in which it is declared.

Characteristics of Local Variables

  • Declared inside a function.
  • Accessible only inside that function.
  • Cannot be accessed from outside the function.
  • Created when the function starts executing.
  • Destroyed after the function finishes execution.

Program: Local Variable

🐍Code Cell
1def f1():
2 a = 10
3 print(a) # Valid
4 
5def f2():
6 print(a) # Invalid
7 
8f1()
9f2()
Output
10

NameError:
name 'a' is not defined

Understanding the Program

The variable a is created inside f1().

Therefore, it is a Local Variable.

It is available only while f1() is executing.

When f2() tries to access it, Python cannot find the variable and raises a NameError.

Lifetime of a Local Variable

Event Local Variable
Function starts Created
Function executes Available
Function ends Destroyed

Difference Between Global and Local Variables

Global Variable Local Variable
Declared outside functions. Declared inside functions.
Accessible throughout the module. Accessible only inside its function.
Can be shared by multiple functions. Cannot be shared outside the function.
Exists throughout program execution. Exists only while the function executes.

Real-World Applications

  • Global variables are used for application-wide configuration settings.
  • Global variables can store constants shared by many functions.
  • Local variables are used for temporary calculations.
  • Loop counters and intermediate results are generally local variables.
  • Keeping temporary values local improves program safety and readability.

The global Keyword

In the previous section, we learned that a Global Variable can be accessed inside a function.

However, if we try to modify a Global Variable directly inside a function, Python creates a new Local Variable instead of modifying the Global Variable.

To modify a Global Variable inside a function, we must use the global keyword.

The global keyword tells Python that the variable belongs to the Global Scope and not to the Local Scope.

Syntax

🐍Code Cell
1global variable_name
Output
No output captured.

Syntax Explanation

Keyword Purpose
global Allows a function to modify a Global Variable.

Example 1 - Accessing a Global Variable

🐍Code Cell
1a = 10
2 
3def display():
4 print(a)
5 
6display()
7 
8print(a)
Output
10
10

Explanation

The variable a is declared outside the function.

Since the function only reads the variable, the global keyword is not required.

Example 2 - Modifying Without global

🐍Code Cell
1a = 10
2 
3def display():
4 a = 20
5 print(a)
6 
7display()
8 
9print(a)
Output
20
10

Explanation

The assignment a = 20 creates a new Local Variable.

The Global Variable remains unchanged.

Therefore, the function prints 20, but outside the function the value is still 10.

Example 3 - Modifying a Global Variable

🐍Code Cell
1a = 10
2 
3def display():
4 global a
5 a = 20
6 print(a)
7 
8display()
9 
10print(a)
Output
20
20

Explanation

The statement global a informs Python that the variable belongs to the Global Scope.

Now the assignment updates the original Global Variable instead of creating a Local Variable.

Therefore, both statements print 20.

Example 4 - Multiple Functions Using global

🐍Code Cell
1count = 0
2 
3def increment():
4 global count
5 count = count + 1
6 
7increment()
8increment()
9increment()
10 
11print(count)
Output
3

Explanation

The Global Variable count is updated every time the function is called.

Since the same Global Variable is modified, the final value becomes 3.

The globals() Function

Python provides the built-in globals() function.

This function returns a Dictionary containing all Global Variables available in the current module.

The Dictionary keys represent variable names, and the values represent the corresponding Global Variable values.

Syntax

🐍Code Cell
1globals()
Output
No output captured.

Example 5 - Using globals()

🐍Code Cell
1a = 10
2b = 20
3 
4print(globals())
Output
{'a': 10, 'b': 20, ...}

Explanation

The globals() function returns a Dictionary.

Besides user-defined Global Variables, the Dictionary also contains several built-in objects created by Python.

For simplicity, only user-defined variables are shown in the sample output.

Example 6 - Accessing Global Variables Using globals()

🐍Code Cell
1a = 100
2b = 200
3 
4print(globals()["a"])
5 
6print(globals()["b"])
Output
100
200

Explanation

The globals() function returns a Dictionary.

Dictionary indexing can be used to access any Global Variable by its name.

Example 7 - Modifying Global Variable Using globals()

🐍Code Cell
1a = 10
2 
3globals()["a"] = 50
4 
5print(a)
Output
50

Explanation

Since globals() returns the Global Namespace Dictionary, changing its value updates the original Global Variable.

Difference Between global Keyword and globals()

global Keyword globals() Function
Used inside a function. Can be used anywhere.
Declares a variable as Global. Returns the Global Namespace Dictionary.
Mainly used to modify Global Variables. Used to view or access all Global Variables.
Keyword. Built-in Function.

Real-World Applications

  • Maintaining application-wide counters.
  • Updating global configuration values.
  • Managing shared application state.
  • Accessing global settings across multiple functions.
  • Debugging by inspecting the Global Namespace.
📝 Key Takeaways
  • A function groups related statements into a reusable unit
  • Functions are defined with def and called by their name
  • Built-in functions like len(), type(), max() and min() are always available
  • Global variables are declared outside functions and are accessible throughout the module
  • The global keyword and globals() function allow modifying global variables from inside a function

🧠 Test Your Knowledge

21 Questions
Progress: 0 / 21