Python Variables Explained with Examples

In Python, a variable is a name given to a value. It acts as a container that holds the value. Variables are essential in programming as they allow us to store, manipulate, and refer to data values throughout the execution of a program.

Naming Variables

Python follows the PEP 8 style guide for naming conventions:

  • Use lowercase letters with words separated by underscores as necessary to improve readability.
  • Avoid using the same name for different variables.
  • Use meaningful names to make the code more understandable.
user_name = "JohnDoe"
total_price = 100.50

How to Use Variables?

To use a variable in Python, you simply assign a value to it using the assignment operator =.

x = 5  # Assign the value 5 to the variable x

Data Types

Python variables are dynamically typed, meaning you don’t need to specify the data type when declaring a variable. The data type of a variable is determined by the value assigned to it.

# Integer
num = 10

# Float
pi = 3.14

# String
name = "Alice"

# Boolean
is_valid = True

# List
numbers = [1, 2, 3, 4]

# Tuple
coordinates = (10, 20)

# Dictionary
person = {"name": "Alice", "age": 30}

# Set
unique_numbers = {1, 2, 3, 4}

Built-in Data Types in Python

Python has several built-in data types, they are:

  • Integers (int): Whole numbers, e.g., 10, -20
  • Floats (float): Decimal numbers, e.g., 3.14, -0.5
  • Strings (str): Sequences of characters, e.g., "Hello", 'World'
  • Boolean (bool): True or False
  • List (list): Ordered, mutable collections, e.g., [1, 2, 3]
  • Tuple (tuple): Ordered, immutable collections, e.g., (1, 2, 3)
  • Dictionary (dict): Unordered collections of key-value pairs, e.g., {"name": "John", "age": 30}
  • Set (set): Unordered collections of unique elements, e.g., {1, 2, 3}
  • None (NoneType): A special constant representing the absence of a value

Assignments

Variables are assigned values using the assignment operator =.

Simple Assignment

x = 5  # Assign 5 to x

Multiple Assignments

x, y, z = 1, 2, 3  # Assign 1 to x, 2 to y, and 3 to z

Swapping Values

x = 5
y = 10
x, y = y, x  # Swap the values of x and y

Chaining Assignments

x = y = z = 10  # Assign 10 to x, y, and z

Augmented Assignments

x = 5
x += 3  # Equivalent to x = x + 3

Scope of Variables

The scope of a variable determines where it can be accessed.

  • Global Variables: Defined outside functions and can be accessed from anywhere.
  • Local Variables: Defined inside functions and are only accessible within those functions.
global_var = "I am a global variable"

def my_function():
    local_var = "I am a local variable"
    print(local_var)

my_function()
print(global_var)