Python: Variables and Data Types

Python variables are at the heart of Python programming and are essential building blocks in creating any program.

In this blog post, we will take a deep dive into the world of Python variables, exploring what they are, how they work, and why they are so important.

What are Python Variables

In Python, variables are containers that store values. Think of them as boxes that hold data such as numbers, strings, or even more complex objects like lists, dictionaries, or functions. Variables are crucial in programming because they allow us to manipulate and work with data, making our programs more dynamic and responsive.

Declaring and Assigning Variables

In Python, declaring a variable is simple. You just choose a name for the variable, and then you assign it a value using the equals sign (=). For example, to declare and assign a variable called “x” with a value of 5, you would write:

x = 5

Here, “x” is the variable name, and 5 is the value assigned to it. Once you have assigned a value to a variable, you can access it and use it in your program.

Python allows you to assign multiple variables in a single line. For example, you can assign three variables “x”, “y”, and “z” to values 1, 2, and 3 respectively in a single line as follows:

x, y, z = 1, 2, 3

Swapping variables

Python allows you to swap the values of two variables using a single line of code. For example, if you have two variables “x” and “y”, you can swap their values as follows:

x, y = y, x

Variable Naming Rules

When choosing variable names in Python, there are a few rules to keep in mind:

  • Variable names can contain letters, numbers, and underscores, but they cannot start with a number.
  • Variable names are case-sensitive, meaning that “x” and “X” are different variables.
  • Avoid using reserved words, such as “if,” “else,” “while,” and “print,” as variable names.

It’s a good practice to follow certain conventions while naming variables in Python. Generally, variable names should be descriptive and indicate what kind of data they store. For example, if you’re storing a person’s age, you could name the variable “age”. Also, variable names in Python are typically written in lowercase letters with underscores separating words (e.g., “my_variable_name”).

Data Types

Every value in Python has a data type. The data type of a variable determines the type of data that can be stored in it and the operations that can be performed on it. Some of the common data types in Python include:

Numbers:

There are three types of numbers in Python: integers, floating-point numbers, and complex numbers.

a = 5               # Integer
b = 3.14            # Floating-point number
c = 2 + 3j          # Complex number

Strings

Strings are sequences of characters enclosed in quotation marks. They can be enclosed in single quotes or double quotes.

name = "John"       # String
address = '123 Main St' # String

Lists

Lists are mutable ordered sequences of elements, which can be of any data type.

numbers = [1, 2, 3, 4]        # List of integers
fruits = ["apple", "banana", "cherry"]  # List of strings
mixed_list = [1, "apple", 3.14]         # List of mixed data types

Tuples

Tuples are immutable ordered sequences of elements, which can be of any data type.

coordinates = (3, 4)        # Tuple of integers
colors = ("red", "green", "blue")  # Tuple of strings
mixed_tuple = (1, "apple", 3.14)         # Tuple of mixed data types

Sets

Sets are unordered collections of unique elements.

letters = {"a", "b", "c"}    # Set of strings
numbers = {1, 2, 3, 4}       # Set of integers
mixed_set = {1, "apple", 3.14}  # Set of mixed data types

Dictionaries

Dictionaries are unordered collections of key-value pairs.

person = {"name": "Sachin", "age": 30, "city": "Bengaluru"}    # Dictionary of strings and integers
employee = {"name": "Anusha", "salary": 50000.0, "department": "CS"}  # Dictionary of strings and floating-point numbers

Booleans

True or False values.

a = False
b =  True

Python is a dynamically-typed language, meaning that you do not have to specify the data type of a variable when you declare it. Python automatically assigns a data type based on the value you assign to the variable.

(With the introduction of PEP 484 – Type Hints | peps.python.org you can specify variable type in Python)

Variable Scope

Variable scope refers to the part of the program where a variable is visible and can be accessed. In Python, there are two types of variable scope: global scope and local scope.

Global scope variables are declared outside of any function and can be accessed from any part of the program. For example:

x = 5

def my_function():
    global x
    x = 10

my_function()
print(x)  # Output: 10

Inside the function, we use the global keyword to indicate that we want to modify the value of the global variable x .

It’s important to use global variables sparingly and with care because they can make it difficult to keep track of where and how the variable is being modified. If possible, it’s better to avoid using global variables altogether and instead pass variables between functions and methods as arguments or return values. This approach can make the code more modular and easier to maintain.

Local scope variables are declared inside a function and can only be accessed within that function. For example:

def my_function():
    x = 5
    print(x)

my_function() # Output: 5