Variables and Data Types

How Python remembers things — and what drawers it has for that.

Fundamentals 12 min Beginner April 26, 2026

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

AnalogyDefinition
Think of a warehouse full of boxes. Each box is an object: it has a fixed spot on the shelf (identity), a label saying what kind of thing it contains (type), and the actual content inside (value). A variable is a sticky note you attach to one of those boxes. The note says "age" and is stuck on the box labeled "integer, value 25." You can peel off the sticky note and stick it on a different box — that is reassignment. You can also put multiple sticky notes on the same box — that is when two variables point to the same object.

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

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: 10 (y 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 integers are immutable.

= 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

Data Type

AnalogyDefinition
Think of materials and tools: objects are made of specific materials — wood (integer), water (string), metal (float). Operators like + are tools. You can glue two pieces of wood together (addition). But you cannot glue wood and water (TypeError). The data type is the material — it determines which tool works. The variable is still just the sticky note attached to the wood or the water.

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.

str Text in quotes: "Hello", 'Python'
int Whole numbers: 0, 42, -7
float Decimal numbers: 3.14, -0.5, 1e6
bool Truth values: True or False
String "42"

"42" + "8" gives "428" (concatenation) type("42") gives <class 'str'>

Integer 42

42 + 8 gives 50 (addition) type(42) gives <class 'int'>

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 allowed

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.

Common operations:Addition (+), subtraction (-), multiplication (*), division (/), floor division (//), modulo (%)
Try these examples:

Type Conversion (Casting): Translating Between Types

Type Conversion (Casting)

AnalogyDefinition
Think of casting as translation between languages. The number 42 is like the concept "forty-two" — it exists independently of language. int(42) is the concept in "number language," str(42) in "text language," and float(42) in "decimal language." Translation works when the meaning transfers: the text "42" can be translated to the number 42. But "hello" cannot be translated to a number — there is no numeric meaning, and Python raises a ValueError, just as a translator would say "this word has no equivalent."

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

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

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().

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!)

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 between text and numbers, Python never converts automatically.

5 + 3.0       # 8.0 (int promoted to float, automatic)
"5" + 3       # TypeError! (no automatic conversion)

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. When an operation fails unexpectedly, type() is your first tool: check whether the variable has the type you expect.

Key Takeaways

  1. A variable in Python is a name that points to an object in memory — it is a label, not a container. Reassignment makes the name point to a new object.
  2. 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.
  3. Python refuses to guess when you mix incompatible types — "5" + 3 raises a TypeError. You must convert explicitly with int(), float(), str(), or bool().
  4. The input() function always returns a string. To do math with user input, you must cast first: int(input("Age: ")).
  5. Use type(x) to check what type a value has — it is your debugging flashlight when operations fail unexpectedly.

Quiz: Test Your Knowledge

Question 1 / 4
Not completed

What is the difference between = and == in Python?

Select one answer
Answer Key: 1) B · 2) B · 3) C · 4) B

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?