Variables in Python [With Examples]

Recently, a new member of the New York Python user group asked me what I should know to become a Python developer. I suggested she learn about Python data types and then Python variables. In this tutorial, I will teach you everything about variables in Python with examples.

In Python, variables are used to store data that can be referenced and manipulated throughout your code. You can declare a variable simply by assigning a value to a name, without needing to specify its type. For example, to store the name of a city and its population, you can write city = "New York" and population = 8419000.

What is a Variable in Python?

A variable in Python is a symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name. Variables can hold different types of data, such as numbers, strings, lists, dictionaries, and more.

Declare a Variable in Python

In Python, you do not need to declare a variable with a specific type. Python is a dynamically typed language, which means the type of a variable is determined at runtime.

# Example of variable declaration
city = "New York"
population = 8419000
area_sq_miles = 468.9

In this example, city is a string variable, population is an integer, and area_sq_miles is a float.

Check out What Is String in Python with Example?

Variable Naming Rules in Python

When naming variables in Python, there are a few rules and conventions to follow:

  1. Variable names must start with a letter or an underscore.
  2. The rest of the name can contain letters, numbers, or underscores.
  3. Variable names are case-sensitive.
  4. It is best practice to use descriptive names.
# Valid variable names
state = "California"
average_income = 75000
is_coastal = True

# Invalid variable names
1st_place = "California"  # Starts with a number
average-income = 75000    # Contains a hyphen
is coastal = True         # Contains a space

Read Python Data Types

Types of Variables in Python

There are different types of variables in Python. Let me show you one by one.

Local Variables

Local variables are defined inside a function and can only be used within that function.

def get_state_population(state):
    population = {
        "California": 39538223,
        "Texas": 29145505,
        "Florida": 21538187
    }
    return population.get(state, "State not found")

print(get_state_population("Texas"))  # Output: 29145505
print(get_state_population("New York"))  # Output: State not found

I executed the above Python code; you can see the exact output in the screenshot below.

Variables in Python

Global Variables

Global variables are defined outside of any function and can be accessed from any function in the code.

# Global variable
country = "United States"

def print_country():
    print(country)

print_country()  # Output: United States

Read Local and Global Variables in Python

Constants

Although Python does not have built-in support for constants (variables that should not change), it is a convention to use all uppercase letters to indicate that a variable is a constant.

# Constant
PI = 3.14159

def calculate_circumference(radius):
    return 2 * PI * radius

print(calculate_circumference(5))  # Output: 31.4159

Check out Install Python Packages in Visual Studio Code

Python Variable Scope

The scope of a variable determines where it can be accessed in the code. Variables can have local or global scope.

Local Scope

A variable declared inside a function is local to that function.

def calculate_tax(income):
    tax_rate = 0.2  # Local variable
    return income * tax_rate

print(calculate_tax(50000))  # Output: 10000
# print(tax_rate)  # Error: NameError: name 'tax_rate' is not defined

Global Scope

A variable declared outside any function is global and can be accessed by any function in the code.

tax_rate = 0.2  # Global variable

def calculate_tax(income):
    return income * tax_rate

print(calculate_tax(50000))  # Output: 10000
print(tax_rate)  # Output: 0.2

Read Install a Python Package from GitHub

Use Python Variables in Real-Life Examples

Let’s explore some real-life examples to understand how variables can be used in Python effectively.

Example 1: Calculate the Sales Tax

Sales tax rates vary by state in the U.S. Let’s write a function to calculate the total price of an item, including sales tax.

def calculate_total_price(price, state):
    sales_tax_rates = {
        "California": 0.0725,
        "Texas": 0.0625,
        "Florida": 0.06
    }
    tax_rate = sales_tax_rates.get(state, 0)
    total_price = price + (price * tax_rate)
    return total_price

price = 100
state = "California"
print(f"Total price in {state}: ${calculate_total_price(price, state):.2f}")
# Output: Total price in California: $107.25

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

Python variables

Example 2: Track COVID-19 Cases

Suppose we want to track the number of COVID-19 cases in different states.

covid_cases = {
    "California": 1000000,
    "Texas": 800000,
    "Florida": 600000
}

def update_cases(state, new_cases):
    if state in covid_cases:
        covid_cases[state] += new_cases
    else:
        covid_cases[state] = new_cases

update_cases("California", 5000)
print(covid_cases["California"])  # Output: 1005000

Example 3: Calculate the Average Temperature

Let’s calculate the average temperature for a week in New York.

temperatures = [85, 87, 84, 82, 88, 90, 86]  # Temperatures in Fahrenheit

def calculate_average_temperature(temps):
    total = sum(temps)
    count = len(temps)
    average = total / count
    return average

average_temp = calculate_average_temperature(temperatures)
print(f"Average temperature in New York: {average_temp:.2f}°F")
# Output: Average temperature in New York: 86.00°F

Conclusion

Variables allow you to store and manipulate data in Python. In this tutorial, we covered the basics of variables in Python, including their types, scope, and naming conventions. I have also explained how to use Python variables with some practical real-time examples.

You may also like the following tutorials:

Leave a Comment