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
Definition
Variable
Analogy
Definition
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).
Note
Step by Step: Tracing Assignment
- 1. x = 10 — Python creates an integer object 10 and attaches the sticky note "x" to it
- 2. y = x — Python attaches a second sticky note "y" to the same object 10
- 3. x = "hello" — Python creates a string object and moves the "x" note; y stays on 10
- 4. print(x) — Output: "hello"x now points to the string
- 5. print(y) — Output: 10y still points to the integer object
Key insight: y = x does not copy the value — it makes y point to the same object. Reassigning x does not affect y, because only the sticky note x is moved — this applies to every type, including lists.
Caution
= Is Not the Same as ==
A single = in Python means "assign," not "equals." For equality comparisons you use ==. If you accidentally write if x = 5: instead of if x == 5:, you get a syntax error. This mix-up is one of the most common beginner mistakes.
Caution with Mutable Objects
With mutable objects like lists, a change through one name is also visible through another: numbers = [1, 2, 3] and then copy = numbers means that copy.append(4) also changes numbers, because both point to the same object. More on this in the article about lists.
Data Types: The Language Your Data Speaks
Definition
Data Type
Analogy
Definition
Real materials can sometimes be combined (you can screw wood and metal together) — Python can do that too: int + float gives a float. Between text and numbers, however, 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, casting creates a new object of a different type from a value.
"42" + "8" gives "428" (concatenation) type("42") gives <class 'str'>
42 + 8 gives 50 (addition) type(42) gives <class 'int'>
Caution
TypeError: Python Does Not Guess
When you mix incompatible types, Python refuses the operation with a TypeError instead of guessing. This protects you from hidden bugs.
"42" + 8 # TypeError: can't add str and int
"Age: " + 25 # TypeError: str + int not allowedNote
type() as a Debugging Tool
text = "The answer is: "
number = 42
print(type(text)) # <class 'str'>
print(type(number)) # <class 'int'>When an operation fails unexpectedly, type() is your first stop: check what type your variable actually has.
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
Definition
Type Conversion (Casting)
Analogy
Definition
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.
Note
The input() Trap: Step by Step
- 1. user_input = input("Your age: ") — User types 25
- 2. type(user_input) is <class 'str'> — it's text, not a number!
- 3. user_input + 5 — TypeError! String and integer cannot be mixed
- 4. age = int(user_input) — now it's an integer, age + 5 gives 30
Note
Casting in Action
user_input = input("Your age: ") # User types 25
print(type(user_input)) # <class 'str'>
age = int(user_input) # now an integer
print(age + 5) # 30
print("You are " + str(age) + " years old.")First convert to a number with int(), then calculate. For text output, convert back to a string with str().
Caution
ValueError: Invalid Conversion
Not every string can be converted to a number. If the content is not a valid numeric format, Python raises a ValueError.
int("hello") # ValueError: invalid literal
float("three") # ValueError: invalid format
int(3.99) # 3 (truncation, not rounding!)Note
Implicit vs. Explicit Conversion
Within numeric types, Python converts automatically: with 5 + 3.0, the 5 is internally converted to 5.0, giving the result 8.0 (float). But with operators like +, Python never converts between text and numbers automatically.
5 + 3.0 # 8.0 (int promoted to float, automatic)
"5" + 3 # TypeError! (no automatic conversion)Caution
Watch Out: bool("0") Is True
The bool() function has special rules: empty values (empty string "", number 0, None) become False, almost everything else becomes True. This means: bool("0") gives True, because "0" is a non-empty string, even though it looks like zero. bool() is not a substitute for real validation.
A valid variable name consists of letters, digits, and underscores, but cannot start with a digit. Case matters: age and Age are different variables. Reserved keywords like if, for, while, True, False, and None cannot be used as variable names.
The Python style guide PEP 8 recommends snake_case for variables: lowercase words separated by underscores, for example max_score or user_name.
A common mistake: using built-in function names as variables. If you write print = 5, you overwrite the print() function in the current namespace and can no longer call it.
In statically typed languages like C or Java, you declare the type: int age = 25; — the name is tied to a type. In Python, the type belongs to the object, not the name: x = 10 and then x = "hello" is valid, because x simply points to a new object.
This makes Python more flexible but also means no compiler catches type mismatches before runtime. If you want that anyway, you can add optional type hints (age: int = 25) and have a checker such as mypy verify them before you run the program; Python itself does not enforce them at runtime. When an operation fails unexpectedly, type() is your first tool: check whether the variable has the type you expect.
Note
Key Takeaways
- A variable in Python is a name that points to an object in memory — it is a sticky note, not a container. Reassignment makes the name point to a new object.
- Every object has a type: str for text, int for whole numbers, float for decimal numbers, bool for True/False. The type determines which operations are allowed.
- Python refuses to guess when you mix incompatible types — "5" + 3 raises a TypeError. You must convert explicitly with int(), float(), str(), or bool().
- The input() function always returns a string. To do math with user input, you must cast first: int(input("Age: ")).
- Use type(x) to check what type a value has — it is your debugging flashlight when operations fail unexpectedly.
Check
Quiz: Test Your Knowledge
What is the difference between = and == in Python?
Select one answer
1. What is the difference between = and == in Python?
2. You have age = 25 (integer). Which code uses explicit casting to output "I am 25 years old" via concatenation?
3. What does type(float("3.14")) return?
4. Consider this code: x = [1, 2, 3] — y = x — y.append(4) — print(x). What is printed and why?
Check
Checkpoint: Do You Understand?
Can you explain this in your own words? Tick what you've got.
0 of 3 done