Variables

Variables in Python

In Python, a variable is a symbolic name that refers to an object or value stored in memory. This allows you to assign descriptive names to data, making it easier to manipulate and reuse values throughout your code. You can create a Python variable by assigning a value using the syntax:

variable_name = value

Python uses the equal sign (=) as the assignment operator. The variable name is placed on the left side of the =, and the value to be assigned is on the right. Python variables are dynamically typed, meaning you don't need to declare their type explicitly. You can reassign a variable to a different value or type by just reassigning it.

# Here, x initially holds an integer and is later reassigned to a string.
x = 42
x = "Hello, World!"

Naming Rules

Consistent and descriptive variable names enhance code readability and maintainability. Python follows specific conventions, primarily outlined in the PEP 8 official style guide for Python code.

Unlike JavaScript that uses CamelCase for everything by convention, Python uses snake_case for variables, which uses underscores to separate words in the variable and uses CamelCase for classes.

All caps are generally used for constants; variables that you will not change.

When naming variables in Python, follow these rules:

  • Start with a letter or underscore: Variable names must begin with a letter (a-z, A-Z) or an underscore (_).
  • Follow with letters, digits, or underscores: After the first character, variable names can include letters, digits (0-9), and underscores.
  • Names are case-sensitive: Variable names are case-sensitive (My_variable and my_variable are different).
  • Avoid reserved words: Do not use Python keywords (e.g., if, else, for) as variable names.

Assigning Multiple Variables

Python allows multiple variable assignments in a single line:

# Here, a is assigned 1, b is assigned 2, and c is assigned 3. 
a, b, c = 1, 2, 3

You can also assign the same value to multiple variables.

# All three variables are assigned the value 0.
x = y = z = 0

Accessing Variables

Once a variable is assigned, you can access its value by referencing its name.

greeting = "Hello, World!"
print(greeting)  # Outputs: Hello, World!

Variables in Python have different scopes:

  • Local Scope: Variables defined within a function are local to that function.
  • Global Scope: Variables defined outside functions are global and accessible throughout the module.
  • Nonlocal Scope: Variables defined in enclosing functions can be accessed using the nonlocal keyword.
def outer_function():
    x = 5
    def inner_function():
        nonlocal x
        x = 10
    inner_function()
    print(x)  # Outputs: 10

Use the global keyword to modify global variables inside functions.

count = 0

def increment():
    global count
    count += 1

Look out for variable shadowing, where a variable in a local scope has the same name as a variable in an outer scope. The local variable "shadows" the outer one. In the following example, the global variable x is shadowed by the local variable x inside my_function. When used inside the function, it essentially reassigns x to the new value. But outside the function it keeps its original or most recent assignment.

x = 5

def my_function():
    x = 10
    print(x)  # Outputs: 10

my_function()
print(x)  # Outputs: 5

Advanced Variable Usage

Python variables can reference mutable or immutable objects. Immutable objects cannot be altered after creation and include:

  • Integers
  • Floats
  • Strings
  • Tuples
x = 10
x = x + 5  # Creates a new integer object

Mutable types can be modified in place and include:

  • Lists
  • Dictionaries
  • Sets
my_list = [1, 2, 3]
my_list.append(4)  # Modifies the existing list

Assigning one variable to another creates an alias, meaning both variables reference the same object. In the following example, modifying b also affects a because they reference the same list object.

a = [1, 2, 3]
b = a
b.append(4)
print(a)  # Outputs: [1, 2, 3, 4]