Module 2 · Core Data Structures ⏱ 19 min

Variables & Data Types

By the end of this lesson you will be able to:
  • Create variables and understand that names point to values
  • Recognise Python's core built-in types: int, float, str, and bool
  • Convert between types and read a value's type at runtime
  • Explain why True and False behave like integers

Before you can manipulate data, you have to know what kind of data you are holding. A number can be multiplied; text cannot. Text can be split into words; a boolean cannot. Python keeps track of these kinds — types — automatically, but it still expects you to understand the difference. Passing the wrong type to an operation is one of the most common sources of beginner errors, and the error messages only make sense once you know what Python is trying to tell you.

In this lesson you will meet Python's four essential types, learn to inspect them at runtime, and practice converting between them safely. These skills are the foundation of every program you will write.

graph TD
  V[Value] --> I["int — 42"]
  V --> F["float — 3.14"]
  V --> S["str — 'hello'"]
  V --> B["bool — True / False"]
  style V fill:#3776ab,color:#fff
Python's four everyday built-in types.

A variable in Python is not a box that holds a value — it is a name that points to a value. When you write age = 30, Python creates the integer 30 and sticks the label age on it. Later, age = 31 does not modify the 30; it peels the label off and sticks it on a brand-new 31. The old 30 is cleaned up automatically when no names point to it anymore.

This matters because two names can point to the same value. a = 30 and b = a both label the same integer. For immutable types like numbers and strings, this is harmless — you cannot change the value in place, so neither name can surprise the other. But it is a critical distinction to keep in mind for the mutable types you will meet later.

Creating variables and inspecting their types.
age = 30
height = 1.75
name = "Ada"
is_learning = True

print(type(age), type(height), type(name), type(is_learning))
print("Next year: " + str(age + 1))
print("Is bool a number?", True + False)
Exercise

A classic conversion. Create a variable celsius set to 25, then create fahrenheit using the formula F = C × 9/5 + 32.

celsius = 25
# create fahrenheit below

Python distinguishes between integers and floating-point numbers by the presence of a decimal point. 42 is an int; 42.0 is a float. You can also write very large integers — Python handles arbitrarily large whole numbers automatically — and floats in scientific notation: 1.5e3 means 1.5 × 10³, or 1500.0. Be careful with division: 10 / 3 always returns a float (3.333...), even when the result is mathematically a whole number. If you need integer division, use //: 10 // 3 gives 3.

flowchart LR
  V1["30"] -->|"age = 30"| A["name: age"]
  V2["31"] -->|"age = 31"| A
  style A fill:#3776ab,color:#fff
Reassignment moves a name to a new value; the old value is discarded when nothing points to it.

You can ask any value what it is with type(). type(42) returns <class 'int'>, type("hello") returns <class 'str'>, and so on. This is useful when you are debugging and a value is behaving strangely — often the type is not what you assumed.

Conversion functions let you build one type from another. int("42") builds an integer from text; str(42) builds text from a number; float("3.14") builds a decimal. But conversion is not magic: int("hello") raises a ValueError, because there is no sensible integer inside that text. The rule is simple — conversion works when the value genuinely represents the target type.

Converting between types and watching truncation.
text = "42"
number = int(text)
print(number, type(number))

pi_text = "3.14159"
pi = float(pi_text)
print(f"Pi ≈ {pi:.2f}")

count = 7
label = str(count)
print("The count is " + label)

print(int(3.9))      # truncates toward zero
print(10 / 3)        # always float
print(10 // 3)       # integer division
Exercise

What does this print? Pay attention to types and the difference between == and is.

a = 5
b = 5.0
c = "5"
print(type(a))
print(type(b))
print(type(c))
print(a == b)
print(a is b)
flowchart LR
  T["True"] -->|"=="| O1["1  (equal)"]
  T -->|"is"| O2["True  (same object)"]
  F["1.0"] -->|"=="| O3["1  (equal)"]
  F -->|"is"| O4["1  (different object)"]
  style T fill:#3776ab,color:#fff
  style F fill:#1e293b,color:#fff
== checks value equality; is checks whether two names point to the exact same object.

Python is dynamically typed, which means a variable's type is determined by the value it currently points to, not by a declaration. x = 10 makes x an integer; x = "ten" makes it a string, in the very same program. This is flexible, but it also means you are responsible for keeping track of what each name holds. A function that expects a number will crash if you hand it a string, and Python will not warn you until the line actually runs.

For large programs, developers add type hints — annotations like def add(a: int, b: int) -> int: — to document what types are expected. Python ignores these at runtime, but tools and editors use them to catch mistakes before you run the code.

Dynamic typing and boolean arithmetic in action.
x = 10
print(type(x))
x = "ten"
print(type(x))

print(True == 1)
print(False == 0)
print(True is True)
print((True + True) * 5)

Booleans in Python are a sub-type of integers: True is 1 and False is 0. This means you can do arithmetic with them, which is occasionally useful and often surprising. True + True equals 2. More practically, sum([True, False, True]) counts how many conditions were met, because each True contributes 1 to the total.

But this also means 1 == True is True, while 1 is True is False. The == operator checks whether values are equal; is checks whether two names point to the exact same object. For simple values the distinction rarely matters, but knowing it exists will save you from a confusing debugging session later on.

Exercise

Write describe(value) that returns the name of the value's type as a string: "int", "float", "str", or "bool". Be careful to check bool before int, because True and False are technically integers in Python.

def describe(value):
    # return 'int', 'float', 'str', or 'bool'
    pass
Exercise

This function is meant to return a sentence combining a player's name and score, but it crashes. Fix it so it works with any name and score.

def report(name, score):
    return "Player " + name + " scored " + score + " points"
Exercise

Write format_measurement(value, unit) that converts value to a float, formats it to one decimal place, and returns a string like "25.0 C". For example, format_measurement("98.6", "F") should return "98.6 F".

def format_measurement(value, unit):
    # convert, format to 1 decimal, append unit
    pass

Recap

  • A variable is a name pointing to a value, not a box that stores it.
  • Python's core types are int, float, str, and bool.
  • Inspect a value's type with type(); convert safely with int(), float(), and str().
  • Python is dynamically typed — a name can point to different types at different times.
  • Booleans are integers in disguise: True == 1 and False == 0.
  • Use == to compare values; reserve is for identity checks.

Next you will learn to read user input and convert it into the types you have just met.

Checkpoint quiz

What is the type of the value 3.14 in Python?

Which expression safely joins the text "Age: " with the number age?

Go deeper — technical resources