Local and Global Variables in Python

If you want to know how to use variables in Python, you should know how to use local and global variables. I will explain local and global variables in Python in detail, with examples.

Local variables in Python are defined within a function and are accessible only within that function, existing only for the duration of the function’s execution. Global variables, on the other hand, are defined outside any function and can be accessed and modified by any function within the program, persisting for the entire duration of the program’s execution. To modify a global variable within a function, the global keyword must be used.

What are Variables in Python?

Variables are containers for storing data values. In Python, a variable is created the moment you first assign a value to it. Unlike some other programming languages, Python does not require you to declare the type of the variable explicitly.

age = 25
name = "John Doe"

In the above example, age is an integer variable, and name is a string variable.

Local Variables in Python

Local variables are those that are defined within a function and their scope is limited to that function. They are created when the function starts execution and are destroyed when the function terminates.

Syntax

To define a local variable in Python, you simply assign a value to a variable name within a function.

def greet():
    message = "Hello, New York!"
    print(message)

In this example, message is a local variable. It exists only within the greet function.

Example

Let me show you an example of how to use local variables in Python.

def calculate_tax():
    income = 50000
    tax_rate = 0.2
    tax = income * tax_rate
    print(f"The tax for an income of ${income} is ${tax}")

calculate_tax()

In this example, income, tax_rate, and tax are local variables. They are used only within the calculate_tax function.

I executed the above Python code, and you can see the output in the screenshot below:

Local Variables in Python

Important Points about Local Variables

  1. Scope: Local variables can only be accessed within the function in which they are defined.
  2. Lifetime: They are created when the function starts and are destroyed when the function ends.
  3. Isolation: Changes to a local variable do not affect variables outside the function.

Read Python Data Types

Global Variables in Python

Global variables in Python are those defined outside any function and are accessible throughout the program. They can be read and modified from any function within the program.

Syntax

To define a global variable in Python, you simply assign a value to a variable name outside of any function.

city = "San Francisco"

def show_city():
    print(f"The city is {city}")

show_city()

In this example, city is a global variable. It can be accessed both inside and outside the show_city function.

Example

Let me show you an example global variable in Python:

population = 8000000

def display_population():
    print(f"The population of the city is {population}")

def increase_population():
    global population
    population += 100000
    print(f"The new population of the city is {population}")

display_population()
increase_population()
display_population()

In this example, population is a global variable. It is accessed and modified by both display_population and increase_population functions.

You can see the output in the screenshot below after I executed the above Python code.

Global Variables in Python

Important Points about Global Variables

  1. Scope: Global variables can be accessed from any function within the program.
  2. Lifetime: They exist for the duration of the program’s execution.
  3. Global Keyword: To modify a global variable within a function, you must use the global keyword.

Read:

Local vs Global Variables in Python

Let me show you the key differences between local and global variables in Python. Here is the summary:

FeatureLocal VariablesGlobal Variables
DefinitionDefined within a functionDefined outside any function
ScopeAccessible only within the functionAccessible throughout the entire program
LifetimeExist only during function executionExist for the duration of the program
DeclarationNo special keyword neededNo special keyword needed
ModificationCannot modify global variables directlyCan be modified using the global keyword
Exampledef func(): var = 10var = 10 outside any function
IsolationChanges do not affect variables outsideChanges can affect program-wide state
Typical Use CaseTemporary calculations within a functionConfiguration settings, constants

Let me show you the differences with an example.

state = "California"

def show_state():
    state = "Nevada"
    print(f"Inside the function, the state is {state}")

show_state()
print(f"Outside the function, the state is {state}")

In this example, the state variable inside the show_state function is a local variable that shadows the global variable state. The output will be:

Inside the function, the state is Nevada
Outside the function, the state is California

This demonstrates how local and global variables with the same name can coexist without interfering with each other.

Local and Global Variables in Python – Real Examples

Let me show you two real examples of using local and global variables in Python.

Use Global Variables for Configuration

Global variables in Python are often used to store configuration settings that need to be accessed by multiple functions. Here is a complete Python program.

config = {
    "api_key": "12345",
    "timeout": 30
}

def get_api_key():
    return config["api_key"]

def set_timeout(new_timeout):
    global config
    config["timeout"] = new_timeout

print(f"API Key: {get_api_key()}")
set_timeout(60)
print(f"New Timeout: {config['timeout']}")

Using Local Variables for Temporary Calculations

Python Local variables are ideal for temporary calculations within functions. Here is a Python code.

def calculate_discount(price, discount_rate):
    discount = price * discount_rate
    final_price = price - discount
    return final_price

price = 100
discount_rate = 0.1
print(f"The final price after discount is ${calculate_discount(price, discount_rate)}")

Conclusion

I hope you know now the difference between local and global variables in Python with real examples. Local variables are confined to the function in which they are defined, providing a controlled environment for temporary calculations. Global variables, on the other hand, offer a way to share data across multiple functions, making them useful for configuration settings and other program-wide data.

I hope this tutorial helps you to understand local and global variables in Python.

You may also like:

Leave a Comment