Variables and Data Types
How Python remembers things — and what drawers it has for that.
Every Python program starts the same way: you give a name to a piece of data. name = "Ada", score = 95, passed = True. These seemingly simple lines raise questions that trip up every beginner at some point: Why does "5" + 3 crash? Why does input() give you text when the user typed a number? And why does changing one variable sometimes change another?
This article answers all three by explaining what variables really are (names, not containers), what data types really do (define the rules for your data), and how to translate between types when Python refuses to mix them.
Variables: Names for Values in Memory
Variable
The box analogy breaks in two places: First, real boxes have fixed sizes, but Python objects like lists can grow dynamically. Second, abandoned boxes in a warehouse do not disappear on their own — but in Python they do (garbage collection).
Step by Step: Tracing Assignment
= Is Not the Same as ==
Caution with Mutable Objects
Data Types: The Language Your Data Speaks
Data Type
Real materials can sometimes be combined (you can screw wood and metal together). In Python, the separation is stricter: str + int is always an error, no exceptions. Also, real materials cannot suddenly change what they are made of — but in Python, an object can get a new type through casting.
"42" + "8" gives "428" (concatenation) type("42") gives <class 'str'>
42 + 8 gives 50 (addition) type(42) gives <class 'int'>
TypeError: Python Does Not Guess
type() as a Debugging Tool
Interactive: Type Detection
Type a Python expression into the input field — a number, text in quotes, True, or a list — and instantly see what data type Python detects and which operations are available. Pay special attention to how "42" (string) differs from 42 (integer).
Type Detection
type(42)→<class 'int'>A whole number without a decimal point. Python integers can grow arbitrarily large.
Type Conversion (Casting): Translating Between Types
Type Conversion (Casting)
The translation analogy breaks at an important point: int(3.99) loses the decimal places — a lossy translation without warning. Also, real languages are ambiguous, but Python casting is deterministic: int("42") always gives exactly 42.
The input() Trap: Step by Step
Casting in Action
ValueError: Invalid Conversion
Implicit vs. Explicit Conversion
Watch Out: bool("0") Is True
Deep Dive: Naming Rules and Conventions
Deep Dive: Why Dynamic Typing Matters
Key Takeaways
Quiz: Test Your Knowledge
Checkpoint: Do You Understand?
- What happens exactly when you first write x = 10 and then x = 20? In what sense does the value 10 still exist afterward?
- Why does print("Age: " + 25) cause an error, and how can you fix the code to produce the same output without errors?
- Why does input() always return a string, and what two steps do you need to perform a calculation with the input?