Variables and Data Types
Variables and Data Types
Section titled “Variables and Data Types”Introduction
Section titled “Introduction”A variable is a named reference to a value stored in memory. Python variables are labels/pointers attached to objects, not containers.
Variables
Section titled “Variables”# Simple assignmentx = 10name = "Alice"pi = 3.14159
# Multiple assignmenta = b = c = 0x, y = 10, 20
# Swap variables (Pythonic!)x, y = y, x
# Extended unpackingfirst, *rest = [1, 2, 3, 4, 5]print(first) # 1print(rest) # [2, 3, 4, 5]Naming Conventions (PEP 8)
Section titled “Naming Conventions (PEP 8)”| Type | Convention | Example |
|---|---|---|
| Variables | snake_case | user_name |
| Constants | UPPER_SNAKE_CASE | MAX_SIZE |
| Classes | PascalCase | UserAccount |
| Functions | snake_case | calculate_tax() |
Data Types Overview
Section titled “Data Types Overview”x = 42 # inty = 3.14 # floats = "hello" # strlst = [1, 2, 3] # listt = (1, 2, 3) # tupled = {"key": "value"} # dictst = {1, 2, 3} # setflag = True # boolnothing = None # NoneTypeflowchart TB subgraph Mutable["Mutable Objects (can change in place)"] direction TB L["list"] D["dict"] S["set"] BA["bytearray"] end
subgraph Immutable["Immutable Objects (cannot change in place)"] direction TB I["int"] F["float"] ST["str"] T["tuple"] BO["bool"] FR["frozenset"] end
style Mutable fill:#1e40af,color:#fff style Immutable fill:#7c3aed,color:#fff style L fill:#2563eb,color:#fff style D fill:#2563eb,color:#fff style S fill:#2563eb,color:#fff style BA fill:#2563eb,color:#fff style I fill:#8b5cf6,color:#fff style F fill:#8b5cf6,color:#fff style ST fill:#8b5cf6,color:#fff style T fill:#8b5cf6,color:#fff style BO fill:#8b5cf6,color:#fff style FR fill:#8b5cf6,color:#fffDynamic Typing
Section titled “Dynamic Typing”x = 5 # intx = "hello" # now strx = [1, 2, 3] # now listType Checking
Section titled “Type Checking”# Preferred: isinstance()print(isinstance(x, int)) # Trueprint(isinstance(x, (int, float))) # True — multiple typesWhy It Matters
Section titled “Why It Matters”Understanding Python’s reference model and dynamic typing is fundamental to writing correct code and avoiding bugs.
Common Mistakes
Section titled “Common Mistakes”- Confusing
=(assignment) with==(comparison) - Not understanding that variables reference objects
- Thinking variables are boxes (they’re labels!)
Interview Questions
Section titled “Interview Questions”Q1: What is dynamic typing in Python?
A: Variable types are determined at runtime. A variable can reference any type of object, and you can change it at any time.
Q2: Why does a = [1,2,3]; b = a; b.append(4) modify a?
A: Because b and a reference the same list object. Variables are labels, not containers.
Practice Exercises
Section titled “Practice Exercises”- Swap two variables without using a third variable.
- Check the type of different values using
type()andisinstance(). - Demonstrate Python’s reference model with lists.