PYTHON FUNDAMENTALS: PROGRAMMING FOUNDATIONS / L02VARIABLES AND BASIC DATA TYPES
课程 · 12 · 02 / 12
LESSON 02 · BEGINNER · 45 MIN · ◆ 3 INSTRUMENTS

Variables and Basic Data Types

Understand how Python stores data with variables and explore fundamental data types like numbers, strings, and booleans.

TIP

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

TIP

💡 Best 60 seconds you can spend on this lesson: open Python Tutor, paste x = [1, 2, 3]; y = x; x.append(4); print(y), and step through it. The arrows showing that x and y point to the same list — that's everything. Once you've seen it, "Python uses references" is permanent knowledge.

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.

FIG. 02Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 02Interactive Python code execution environment

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
FIG. 04Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 04Interactive Python code execution environment

Python's Built-in Data Types

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

1. Numbers (int and float)

FIG. 06Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 06Interactive Python code execution environment

2. Strings (Text Data)

FIG. 08Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 08Interactive Python code execution environment

3. Booleans (True/False)

FIG. 10Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 10Interactive Python code execution environment

Memory Visualization

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

FIG. 12Memory Visualizer
INTERACTIVE
LOADING INSTRUMENT
Fig. 12Visual representation of memory layout
FIG. 14Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 14Interactive Python code execution environment

Type Conversion

Python can convert between different data types:

FIG. 16Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 16Interactive Python code execution environment

Variable Tracker in Action

Let's see multiple variables working together:

FIG. 18Variable Tracker
INTERACTIVE
LOADING INSTRUMENT
Fig. 18Visual tracking of variable states and memory addresses

Dynamic Typing

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

FIG. 20Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 20Interactive Python code execution environment

Practical Examples

Example 1: User Profile

FIG. 22Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 22Interactive Python code execution environment

Example 2: Temperature Converter

FIG. 24Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 24Interactive Python code execution environment

Common Mistakes to Avoid

FIG. 26Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 26Interactive Python code execution environment

Practice Exercises

Exercise 1: Personal Information

FIG. 28Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 28Interactive Python code execution environment

Exercise 2: Shopping Calculator

FIG. 30Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 30Interactive Python code execution environment

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!


Further Reading

Visualize What's Happening

  • Python Tutor — paste a few x = 5; y = x; x = 7 lines and see with arrows that integers are immutable and lists are mutable. The single best way to internalize "what is a Python variable, really."
  • Setosa — Visualizing Number Formats — interactive demo of how integers and floats are stored. Helps when 0.1 + 0.2 != 0.3 becomes confusing.

Official Docs

Tutorials

Books & References

  • Book: Fluent Python (2nd ed., 2022) — Luciano Ramalho, O'Reilly. Chapter 1 ("Python Data Model") will reframe how you think about types.
  • Book: Effective Python (3rd ed., 2024) — Brett Slatkin. Items 4–10 cover string and numeric idioms.
  • learnxinyminutes — Python — types section as a one-page reference you can bookmark.