Back to Learning Area

Variables and Data Types

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

  • Fundamentals
  • 12 min
  • Beginner

Plain Language

This preview is in Plain Language. The whole portal is also available in Plain Language. You can change the language at the top. Or use the button below. Our Plain Language texts are AI-assisted and editorially reviewed. They follow the core principles of easy-to-read language, but they are not certified Easy Read: a review panel of people with learning difficulties does not test them.

Preview: Variables and data types in Python

What are variables?

This page explains variables in Python. Python is a programming language. A variable is a name for a value. Example: points = 95. The name 'points' points to the number 95.

What are data types?

Every value has a type. Text is called a string. String means: a sequence of letters. Whole numbers are called integers. Integer means: whole number without a decimal point.

Do not mix types

Python does not allow mixing types. You cannot add text and numbers. This gives an error. You must convert the type first. This is called casting. Casting means: changing the type.

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

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

Note

Step by Step: Tracing Assignment

  1. 1. x = 10 — Python creates an integer object 10 and attaches the sticky note "x" to it
  2. 2. y = x — Python attaches a second sticky note "y" to the same object 10
  3. 3. x = "hello" — Python creates a string object and moves the "x" note; y stays on 10
  4. 4. print(x) — Output: "hello"x now points to the string
  5. 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

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

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'>

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 allowed

Note

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

Controls
Input
Examples
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 (%)

Type Conversion (Casting): Translating Between Types

Definition

Type Conversion (Casting)

Analogy

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.

Note

The input() Trap: Step by Step

  1. 1. user_input = input("Your age: ") — User types 25
  2. 2. type(user_input) is <class 'str'> — it's text, not a number!
  3. 3. user_input + 5 — TypeError! String and integer cannot be mixed
  4. 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

  1. 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.
  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.

Check

Quiz: Test Your Knowledge

Not completed

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

Select one answer

Answer Key: 1) B · 2) B · 3) C · 4) B

Check

Checkpoint: Do You Understand?

Can you explain this in your own words? Tick what you've got.

0 of 3 done