Python
Variables

A Guide to Variables in Python

Variables are essential components of any programming language, including Python. They serve as containers to store data and allow us to manipulate information in various ways. In this post, we will be covering everything you need to know to master this fundamental concept.

Introduction to Variables

Definition and Purpose

In Python, a variable is a symbolic name that represents a value stored in memory. It acts as a reference to the data, allowing us to access and modify it easily. Variables are crucial for data manipulation, calculations, and storing results for future use.

Naming Rules and Conventions

Python has specific rules for naming variables:

  • Variable names must start with a letter (a-z, A-Z) or an underscore (_).
  • They can be followed by letters, underscores, or digits (0-9).
  • Variable names are case-sensitive (myVar and myvar are different variables).
  • Avoid using reserved keywords as variable names (e.g., if, while, for).

Data Types in Python

Python is a dynamically-typed language, meaning you don't need to declare a variable's type explicitly. Python determines the data type based on the assigned value.

Code Example:

# Integer variable
age = 25
 
# Float variable
pi = 3.14
 
# String variable
name = "John Doe"
 
# Boolean variable
is_student = True

Variable Assignment

Initializing Variables

To assign a value to a variable, you use the assignment operator =. The variable is created if it doesn't exist and updated if it does.

Code Example:

x = 10      # Integer variable
y = 3.14    # Float variable
name = "Alice"  # String variable
is_ready = True # Boolean variable

Dynamic Typing in Python

Unlike statically-typed languages, Python allows variables to change their data type during execution.

Code Example:

x = 10
print(x)     # Output: 10
 
x = "Hello"
print(x)     # Output: Hello

Multiple Assignments and Swapping Values

Python allows multiple assignments in a single line and swapping values of variables in an elegant way.

Code Example:

a, b, c = 1, 2.5, "Python"
print(a, b, c)   # Output: 1 2.5 Python
 
# Swapping values
x, y = 10, 20
x, y = y, x
print(x, y)   # Output: 20 10

Variable Scope

Below is a one-liner introduction to local, global and non-local variables. For thorough understanding, refer to post on Scope and Namespace

Local Variables

Variables defined inside a function are called local variables. They are only accessible within that function's scope.

Code Example:

def my_function():
    age = 25    # Local variable
    print(age)
 
my_function()   # Output: 25
 
# Trying to access the local variable outside the function will raise an error
print(age)      # NameError: name 'age' is not defined

Global Variables

Variables defined outside any function or block have global scope and can be accessed from anywhere in the program.

Code Example:

x = 10    # Global variable
 
def my_function():
    print(x)   # Accessing the global variable
 
my_function()   # Output: 10

Nonlocal Variables

When a variable is neither local nor global, it may be a nonlocal variable, typically encountered in nested functions.

Code Example:

def outer_function():
    x = "local"
 
    def inner_function():
        nonlocal x
        x = "nonlocal"
        print("Inner:", x)
 
    inner_function()
    print("Outer:", x)
 
outer_function()
# Output:
# Inner: nonlocal
# Outer: nonlocal

Constants in Python

Using Uppercase Convention

Although Python does not have constants in the traditional sense, developers use uppercase variable names to represent constant values that should not be changed during the program's execution.

Code Example:

PI = 3.14159
DAYS_IN_A_WEEK = 7

The const Module (Python 3.8+)

In Python 3.8 and later, you can use the const module to create constant-like behavior.

Code Example:

from const import const
 
const.PI = 3.14159
const.DAYS_IN_A_WEEK = 7

Python's Built-in Functions for Variables

id(): Identifying Memory Address

The id() function returns the unique memory address of an object, useful for comparing object identity.

Code Example:

x = 10
y = x
 
print(id(x))    # Output: <memory address>
print(id(y))    # Output: <same memory address as x>

type(): Determining Data Type

The type() function allows you to determine the data type of a variable or an object.

Code Example:

x = 10
y = "Hello"
z = [1, 2, 3]
 
print(type(x))    # Output: <class 'int'>
print(type(y))    # Output: <class 'str'>
print(type(z))    # Output: <class 'list'>

del: Deleting Variables

The del statement is used to delete variables or objects from memory.

Code Example:

x = 10
print(x)    # Output: 10
 
del x
print(x)    # NameError: name 'x' is not defined

Variables are the backbone of any programming language, including Python. Understanding how to create, assign, and use variables is fundamental to writing effective and efficient code.