Variables and Basic Data Types

Learning Objectives: After this lesson, you'll understand how Python stores data with variables, explore fundamental data types, and see how Python manages memory automatically.

Understanding Variables

Think of variables as labeled containers that store data. Unlike some programming languages, Python variables are more like name tags attached to data rather than fixed storage boxes.

Loading Python runtime...

Variable Naming Rules

Python has specific rules for naming variables:

✅ Valid❌ InvalidWhy?
user_nameuser-nameNo hyphens allowed
age22ageCan't start with number
_privateclassclass is a reserved word
firstNamefirst nameNo spaces allowed

Loading Python runtime...

Python's Built-in Data Types

Python has several fundamental data types. Let's explore each one:

1. Numbers (int and float)

Loading Python runtime...

2. Strings (Text Data)

Loading Python runtime...

3. Booleans (True/False)

Loading Python runtime...

Memory Visualization

Let's see how Python manages memory for different variables:

Loading interactive component...

Loading Python runtime...

Type Conversion

Python can convert between different data types:

Loading Python runtime...

Variable Tracker in Action

Let's see multiple variables working together:

Loading interactive component...

Dynamic Typing

Python is dynamically typed, meaning variables can change their type:

Loading Python runtime...

Practical Examples

Example 1: User Profile

Loading Python runtime...

Example 2: Temperature Converter

Loading Python runtime...

Common Mistakes to Avoid

Loading Python runtime...

Practice Exercises

Exercise 1: Personal Information

Loading Python runtime...

Exercise 2: Shopping Calculator

Loading Python runtime...

Key Takeaways

Variables are labels - They point to data in memory, not storage boxes
Dynamic typing - Variables can change type during program execution
Four basic types - int, float, str, bool cover most basic needs
Type conversion - Use int(), float(), str(), bool() to convert between types
Good naming - Use descriptive, consistent variable names
Memory management - Python handles memory automatically

Connections: Variables Across Mathematics, Programming, and Beyond

🔗 Connection to Mathematics

Variables in programming are directly inspired by mathematical variables, but with key differences:

Mathematical Variables:

Algebra: x + 5 = 10 (x is unknown, we solve for it) x = 5 Function: f(x) = x² + 3x + 2 f(2) = 4 + 6 + 2 = 12

Python Variables:

# Similar to algebra x = 5 y = x + 10 # y = 15 # Similar to functions def f(x): return x**2 + 3*x + 2 result = f(2) # result = 12

Key Similarities:

  • Both store values that can change
  • Both can be used in calculations
  • Both use symbolic names (x, y, z or age, name, price)
  • Both follow order of operations

Key Differences:

  • Math variables: Typically unknown values we solve for
  • Python variables: Known values we assign and manipulate
  • Math variables: Usually single letters (x, y, z)
  • Python variables: Descriptive names (user_age, total_price)
  • Math variables: Type is implicit (assume real numbers)
  • Python variables: Type is explicit (int, float, str, bool)

🔗 Connection to Other Languages

Variables work differently across programming languages:

PythonJavaScriptJavaC++
x = 5let x = 5int x = 5;int x = 5;
Dynamic typingDynamic typingStatic typingStatic typing
x = "hello" ✅ OKx = "hello" ✅ OK❌ Type error❌ Type error
Auto memory mgmtAuto memory mgmtAuto memory mgmtManual memory mgmt

Python's Advantage:

  • Dynamic typing: More flexible, easier for beginners
  • No declarations: Just assign and go
  • Type inference: Python figures out the type

Tradeoff:

  • Less safety (type errors only at runtime)
  • Slightly slower (type checking overhead)
  • Requires more discipline with naming

🔗 Connection to Real-World Concepts

Variables are like:

  1. Spreadsheet Cells

    • Cell A1 holds a value (like variable x)
    • You can reference it in formulas (=A1*2)
    • Value can change, formulas update automatically
  2. Labels on Storage Boxes

    • Box labeled "Winter Clothes" (variable name)
    • Contents inside (the value)
    • Can relabel box for different contents (reassignment)
  3. Contacts in Phone

    • Contact name "Mom" (variable name)
    • Phone number stored (the value)
    • Name stays same, can update number (reassignment)

🔗 Connection to Computer Science Fundamentals

Memory Management:

Computer Memory (RAM): ┌─────────────────────────────────┐ │ Address | Value | Variable │ ├─────────────────────────────────┤ │ 0x1000 │ 25 │ age │ │ 0x1004 │ "Bob" │ name │ │ 0x1008 │ 3.14 │ pi │ └─────────────────────────────────┘

How Python Variables Work:

  1. Assignment: Creates label pointing to memory location
  2. Reassignment: Points label to new memory location
  3. Garbage collection: Cleans up unused memory automatically
  4. Reference counting: Tracks how many labels point to each value

🔗 Connection to Future Python Topics

Variables are the foundation for:

  • Functions: Parameters and return values are variables
  • Classes: Attributes are variables attached to objects
  • Scope: Understanding where variables are accessible
  • Data structures: Lists, dicts store multiple variables
  • Loops: Loop variables iterate over collections
  • Closures: Functions that remember variables from outer scope

🔗 Connection to Type Systems

Python's Type System:

  • Dynamic: Type determined at runtime
  • Strong: Can't add string + int without explicit conversion
  • Duck typing: "If it walks like a duck and quacks like a duck..."

Comparison:

# Python (dynamic, strong) x = 5 x = "hello" # ✅ OK - type can change print(x + 5) # ❌ TypeError - can't add string + int # JavaScript (dynamic, weak) let x = 5 x = "hello" // ✅ OK console.log(x + 5) //"hello5" - automatic coercion # Java (static, strong) int x = 5; x = "hello"; // ❌ Compile error - type is fixed

🔗 Connection to Data Science

In data science, variables represent data:

# Statistical variables mean = sum(data) / len(data) std_dev = calculate_std_dev(data) # Data variables (like spreadsheet columns) ages = [25, 30, 35, 40, 45] names = ["Alice", "Bob", "Charlie", "Diana", "Eve"] # Each list is like a variable column in a dataset

🔗 Historical Evolution

Variables have evolved with programming languages:

  • 1940s: Machine code (no variables, just memory addresses)
  • 1950s: Assembly language (symbolic names for addresses)
  • 1957: FORTRAN (first high-level variables)
  • 1960s-70s: Variables with types (Pascal, C)
  • 1990s: Dynamic typing becomes popular (Python, Ruby)
  • 2020s: Type hints in dynamic languages (Python 3.5+)

Python's Modern Approach:

# Original Python (dynamic, no hints) def add(a, b): return a + b # Modern Python (dynamic with optional type hints) def add(a: int, b: int) -> int: return a + b

Remember: Variables are the fundamental building blocks of all programs. Master them, and everything else becomes easier!

Next Steps

In the next lesson, we'll learn about making decisions with conditions - how to use if statements, comparison operators, and boolean logic to control program flow.


Ready to make your programs smarter? The next lesson will teach you how to make decisions in code!