Python Variables – Complete Guide

If you want to become a good Python developer or programmer, then you should know everything about Python variables, including variable naming rules, type of variables, variable scopes, etc. In this tutorial, I have explained all these things about variables in Python with examples. So, I hope it will help both beginners and experienced Python developers.

Let’s learn in detail.

What Are Variables in Python?

In programming, a variable is a named location used to store data in memory. Think of a variable as a container that holds information that can be changed later. In Python, variables are created when you assign a value to them using the assignment operator =.

For example:

city = "New York"
population = 8419000
area = 468.9

In the above example, citypopulation, and area are variables. The variable city is assigned the string value "New York"population is assigned the integer value 8419000, and area is assigned the floating-point number 468.9.

Python Variable Naming Rules

Naming conventions are very important in any programming language, so as in Python. Let me tell you a few best practices or rules for naming variables in Python:

  1. Variable names must start with a letter (a-z, A-Z) or an underscore (_).
  2. The rest of the name can contain letters, digits (0-9), or underscores.
  3. Variable names are case-sensitive. For example, city and City are two different variables.
  4. Reserved words (keywords) cannot be used as variable names. These are words that have special meaning in Python, such as ifelsewhilefor, etc.

Read How to Check if a Variable Exists in Python?

Types of Variables in Python

Python supports several data types, and variables can hold values of different types. Here are the most common types of variables in Python with examples:

1. Integer Variables

Integer variables in Python hold whole numbers, positive or negative, without any decimal point. In Python, you can create an integer variable by assigning an integer value to it.

age = 30
year = 2024
temperature = -5

2. Floating-Point Variables

Floating-point variables hold numbers with a decimal point. They represent real numbers. Here is an example.

average_income = 55234.75
height = 5.9
rainfall = 12.3

3. String Variables

String variables in Python hold sequences of characters enclosed in single quotes (') or double quotes ("). Strings are used to represent text.

first_name = "John"
last_name = 'Doe'
address = "1234 Elm Street, Springfield, IL"

Read How to Check if a Variable is an Empty String in Python?

4. Boolean Variables

Boolean variables in Python hold one of two values: True or False. They are used to represent truth values.

is_registered_voter = True
has_drivers_license = False

5. List Variables

Python Lists are ordered collections of items (elements) that can be of different types. Lists are mutable, meaning their content can be changed after creation.

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
ages = [25, 30, 35, 40, 45]
temperatures = [72.5, 68.0, 75.2, 70.1]

6. Tuple Variables

Tuples in Python are similar to lists, but they are immutable, meaning once created, their content cannot be changed. Tuples are defined by enclosing elements in parentheses (()).

coordinates = (40.7128, -74.0060)  # Latitude and Longitude of New York City
dimensions = (1920, 1080)  # Width and Height

7. Dictionary Variables

Dictionaries in Python are unordered collections of key-value pairs. Each key is unique, and values can be of any type. Dictionaries are defined using curly braces ({}).

state_population = {
    "California": 39538223,
    "Texas": 29145505,
    "Florida": 21538187,
    "New York": 20201249
}

person = {
    "first_name": "Jane",
    "last_name": "Smith",
    "age": 28,
    "city": "San Francisco"
}

8. Set Variables

Python Sets are unordered collections of unique elements. Sets are defined using curly braces ({}) or the set() function.

unique_numbers = {1, 2, 3, 4, 5}
vowels = set("aeiou")

Read Add Two Variables in Python

How to Use Python Variables With Examples?

Let me show you some practical examples to see how these different types of variables can be used in Python programming.

Example 1: Calculate the Area of a Circle

Let’s calculate the area of a circle given its radius. We will use an integer variable for the radius and a floating-point variable for the area.

Here is the complete code where we have used two variables to calculate the area of a circle in Python.

import math

radius = 7
area = math.pi * radius ** 2

print(f"The area of the circle with radius {radius} is {area:.2f}")

I executed the above code using Visual Studio code, and you can see the output in the screenshot below:

Python Variables

Example 2: Store and Retrieve User Information

Let’s create a Python dictionary variable to store user information and retrieve specific details.

Here is the Python code for storing and retrieving user information using a dictionary variable.

user_info = {
    "username": "johndoe",
    "email": "johndoe@example.com",
    "age": 35,
    "city": "Chicago"
}

print(f"Username: {user_info['username']}")
print(f"Email: {user_info['email']}")
print(f"Age: {user_info['age']}")
print(f"City: {user_info['city']}")

You can see the screenshot below for the output after I executed the above Python code:

Python Variables examples

Example 3: Manage a List of Products

Let’s create a list of products and perform some operations on it.

Below is the code to check Managing a List of Products,

products = ["Laptop", "Smartphone", "Tablet", "Smartwatch"]

# Adding a new product
products.append("Headphones")

# Removing a product
products.remove("Tablet")

# Sorting the list
products.sort()

print("Available products:")
for product in products:
    print(product)

I executed the above Python code using Visual Studio code, and you can see the output in the screenshot below.

how to use python variables

Example 4: Work with Tuples

Let’s use tuples to store and print geographical coordinates.

Here is the code you can follow to learn how to use Tuples variables in Python.

nyc_coordinates = (40.7128, -74.0060)
sf_coordinates = (37.7749, -122.4194)

print(f"New York City Coordinates: Latitude = {nyc_coordinates[0]}, Longitude = {nyc_coordinates[1]}")
print(f"San Francisco Coordinates: Latitude = {sf_coordinates[0]}, Longitude = {sf_coordinates[1]}")

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

python variable usage

Example 5: Use Sets to Find Unique Elements

Let’s use sets to find unique elements in a list.

Below is the python code,

numbers = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7]

unique_numbers = set(numbers)

print(f"Original list: {numbers}")
print(f"Unique numbers: {unique_numbers}")

I executed the above Python code using Sets to Find Unique Elements. Below is my output with a screenshot.

Types of Variables in Python

Python Variable Scope

In Python, the scope of a variable determines where that variable can be accessed. There are two main types of scope:

  1. Global Scope: There are the variables in Python that are defined outside any function are in the global scope and can be accessed anywhere in the code.
  2. Local Scope: Variables in Python that are defined inside a function are in the local scope and can only be accessed within that function.

Global Variables in Python

Python Global variables are accessible from any part of the program.

Here’s the Python code for the Global Variable:

city = "Boston"

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

print_city()  # Outputs: The city is Boston

You can see the screenshot below after I execute the Python code.

Global Variables in Python

Local Variables in Python

Local variables in Python are only accessible within the function they are defined in.

Here’s a complete Python code where I have explained how to use a local variable:

def calculate_sum():
    a = 10
    b = 20
    result = a + b
    print(f"The sum is {result}")

calculate_sum()  # Outputs: The sum is 30

# Trying to access 'a' or 'b' outside the function will result in an error
# print(a)  # NameError: name 'a' is not defined

Below the screenshot, you can see the output after I execute the Python code:

Local Variables in Python

Global Keyword in Python

If you need to modify a global variable inside a function, you can use the global keyword.

Here is the complete Python code using the Global keyword in Python:

count = 0

def increment():
    global count
    count += 1

increment()
print(f"Count after incrementing: {count}")  # Outputs: Count after incrementing: 1

I executed the above Python code; the output is in the screenshot below.

Global Keyword in Python

Variable Type Conversion

Sometimes, you may need to convert variables from one type to another. Python provides several built-in functions for type conversion:

  • int(): Converts a value to an integer.
  • float(): Converts a value to a float.
  • str(): Converts a value to a string.
  • list(): Converts a value to a list.
  • tuple(): Converts a value to a tuple.
  • set(): Converts a value to a set.

Example of Type Conversion

Let’s look at an example where we convert different types of variables:

# Converting a string to an integer
str_value = "100"
int_value = int(str_value)
print(f"Integer value: {int_value}")

# Converting an integer to a float
int_value = 50
float_value = float(int_value)
print(f"Float value: {float_value}")

# Converting a list to a tuple
list_value = ["apple", "banana", "cherry"]
tuple_value = tuple(list_value)
print(f"Tuple value: {tuple_value}")

# Converting a tuple to a set
tuple_value = (1, 2, 3, 4, 5)
set_value = set(tuple_value)
print(f"Set value: {set_value}")

Best Practices for Using Variables in Python

Here are some best practices to follow when using variables in Python:

  • Use meaningful names: Choose variable names that clearly describe the data they hold. This makes your code more readable and maintainable.
# Bad variable names
a = "John"
b = 30

# Good variable names
first_name = "John"
age = 30
  • Follow naming conventions: Use lowercase letters and underscores for variable names (snake_case). This is the standard convention in Python.
total_amount = 100.50
customer_name = "Alice"
  • Avoid using reserved words: Do not use Python keywords as variable names.
# Bad practice
if = 10  # SyntaxError: invalid syntax

# Good practice
condition = 10
  • Initialize variables: Always initialize variables before using them. This prevents errors and makes your code more predictable.
# Bad practice
total += 10  # NameError: name 'total' is not defined

# Good practice
total = 0
total += 10
  • Use constants for fixed values: If a value should not change, use a constant. Constants are usually written in uppercase letters.
PI = 3.14159
MAX_USERS = 100

Conclusion

Variables allow you to store and manipulate data in Python. In this tutorial, I explained different types of variables, including integers, floats, strings, booleans, lists, tuples, dictionaries, and sets. We also checked variable scope, type conversion, and best practices for using variables.

I hope you will know how to use Python variables from all the examples above.

You may like the following tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.