2. Python Variables

Python Variables - including theory, types, edge cases, memory, naming conventions, user input, unpacking, scope, mutation, and more.

Pre-Test exercise here

Table of Contents

  1. What is a Variable?
  2. Variable Naming Rules
  3. Assigning Values
  4. Data Types
  5. Type Casting
  6. Multiple Assignments
  7. Unpacking Sequences
  8. Constants
  9. User Input and Variables
  10. Variable Scope (Local, Global, Nonlocal)
  11. Mutable vs Immutable Variables
  12. Memory Management
  13. Deleting Variables
  14. Useful Functions with Variables
  15. Edge Cases and Pitfalls
  16. Practice Exercises

1. What is a Variable?

A variable is a named reference to a location in memory where data is stored.

Examples:

x = 10
name = "Alice"
height = 5.9
is_admin = True

2. Variable Naming Rules

Valid:

  • Start with a letter or underscore.
  • Contain letters, numbers, and underscores.
  • Case-sensitive.

Invalid:

  • Cannot start with a number.
  • Cannot use Python keywords (for, if, while, etc).

Examples:

_my_var = 1
userName = "Tom"
score123 = 45

Invalid:

1score = 10        # Error
for = 5            # 'for' is a keyword

3. Assigning Values

Basic:

x = 5
y = "Hello"

Chain Assignment:

a = b = c = 100

Simultaneous Assignment:

x, y = 1, 2

Swapping:

a, b = b, a

4. Data Types in Variables

TypeExample
intx = 10
floatpi = 3.14
strname = "Alice"
boolis_valid = True
listnums = [1, 2, 3]
tuplet = (1, 2)
dictd = {"a": 1}
sets = {1, 2, 3}
Nonex = None

Use type() to find a variable's data type:

print(type(x))  # <class 'int'>

5. Type Casting

Convert one type to another.

Examples:

a = "100"
b = int(a)         # String to int
c = float(b)       # Int to float
d = str(c)         # Float to string

Common Pitfall:

x = int("10.5")    # ValueError: invalid literal

6. Multiple Assignments

a, b, c = 1, 2, 3
x = y = z = "same"

With operations:

x, y = y, x + y

7. Unpacking Sequences

Python allows sequence unpacking into variables.

Tuple or List:

data = [10, 20, 30]
a, b, c = data

Extended Unpacking:

a, *b, c = [1, 2, 3, 4, 5]
# a=1, b=[2,3,4], c=5

8. Constants in Python

Python doesn't have built-in constants. Use uppercase to signify that a variable is constant.

PI = 3.14159
MAX_USERS = 100

9. User Input and Variables

name = input("Enter your name: ")         # Always returns string
age = int(input("Enter your age: "))      # Convert input to int
price = float(input("Enter price: "))     # Convert input to float

Example:

n1 = int(input("Enter 1st number: "))
n2 = int(input("Enter 2nd number: "))
print("Sum:", n1 + n2)

10. Variable Scope

Global Variable:

x = 10

def show():
    print(x)

show()  # 10

Local Variable:

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

func()  # 5

Changing Global:

x = 5

def update():
    global x
    x = 20

update()
print(x)  # 20

nonlocal Keyword:

Used inside nested functions.

def outer():
    x = 10
    def inner():
        nonlocal x
        x = 20
    inner()
    print(x)  # 20

11. Mutable vs Immutable Variables

Immutable:

int, float, str, bool, tuple

x = 10
y = x
y += 1
print(x, y)  # 10, 11

Mutable:

list, dict, set

a = [1, 2]
b = a
b.append(3)
print(a)  # [1, 2, 3] — affected!

Use copy() to prevent this:

b = a.copy()

12. Memory Management

Python manages memory using reference counting and garbage collection.

Use id() to get memory location:

x = 100
print(id(x))  # Memory address

13. Deleting Variables

x = 10
del x
# print(x)  # NameError

14. Useful Functions with Variables

# type() → data type
print(type(10))        # <class 'int'>

# isinstance() → check type
print(isinstance(10, int))  # True

# id() → memory location
print(id("hello"))

15. Edge Cases and Pitfalls

Assigning Mutable Defaults in Functions

def add_item(item, container=[]):
    container.append(item)
    return container

print(add_item("A"))  # ['A']
print(add_item("B"))  # ['A', 'B'] ❗ Unexpected!

Use this instead:

def add_item(item, container=None):
    if container is None:
        container = []
    container.append(item)
    return container

16. Practice Exercises

Exercise 1:

Write a program that takes name and age and prints them.

name = input("Name: ")
age = int(input("Age: "))
print(f"{name} is {age} years old.")

Exercise 2:

Swap two variables without a temp variable.

x, y = 5, 10
x, y = y, x

Exercise 3:

Create a program to input 3 numbers and output the average.

a = float(input("Enter 1st: "))
b = float(input("Enter 2nd: "))
c = float(input("Enter 3rd: "))
avg = (a + b + c) / 3
print("Average:", avg)

Summary Table

ConceptExample
Assignmentx = 10
Multiple Assignmentsx, y = 1, 2
Unpackinga, *b, c = [1,2,3,4,5]
ConstantsMAX_LIMIT = 100
Inputinput("Name?")
Type Conversionint("100"), str(10)
Mutable Typeslist, dict, set
Immutable Typesint, float, str, tuple
Scope TypesGlobal, Local, Nonlocal