O
Octo
O
Octo
CoursesPricingDashboardPrivacyTerms

© 2026 Octo

Python Fundamentals
1Why Python2Variables & Data Types3Control Flow4Functions5Data Structures6Working with Files & Data7Libraries & Packages8Your First Python Project
Module 2

Variables & Data Types

Variables are labeled boxes that hold your data — learn strings, numbers, booleans, and type conversion, the building blocks of every Python program.

The spreadsheet that saved a hospital

In 2020, a public health team in a UK hospital was tracking COVID-19 cases in an Excel spreadsheet. One morning, 16,000 positive test results vanished. The team panicked — had the data been deleted? Hacked?

Neither. Excel had a row limit of 65,536 rows in the older .xls format they were using. When the data exceeded that limit, Excel silently dropped the overflow. Nobody noticed for days. The result: 16,000 people with COVID were not contacted for contact tracing.

The root cause was not a virus or a cyberattack. It was a data type problem. The team was using a tool that stored data in a format with hard limits they did not understand. If they had used Python — where you explicitly choose how to store your data — they would have caught the problem immediately, because Python does not silently lose your data.

This module teaches you how Python stores information: variables and data types. These are the building blocks of every program you will ever write.

16000COVID cases lost due to data type error

4core data types in Python

1 lineto create a variable in Python

Variables — labeled boxes for your data

Imagine you are moving into a new apartment. You pack your belongings into boxes and write labels on each one: "Kitchen," "Books," "Clothes." The label tells you what is inside without opening the box.

A variable in Python works the same way. It is a label attached to a piece of data. You create one by writing a name, an equals sign, and a value:

age = 25
name = "Sarah"
is_student = True
temperature = 98.6

That is it. No special keywords, no type declarations. Python figures out the type automatically.

ConceptReal-world analogyPython example
Variable nameThe label on the boxage, name, price
ValueWhat is inside the box25, "Sarah", 19.99
Assignment (=)Taping the label onto the boxage = 25
ReassignmentReplacing the contentsage = 26
⚠️The equals sign does not mean 'equals'
In math, `x = 5` means "x is equal to 5." In Python, `x = 5` means "put the value 5 into the box labeled x." This is called **assignment**, not equality. To check if two things are equal, Python uses `==` (double equals). This trips up every single beginner — now it will not trip you up.

Naming rules

Python has a few rules for variable names:

# Valid names
user_name = "Alice"
score1 = 95
_private = "hidden"
totalAmount = 500

# Invalid names — these will crash
1score = 95       # Cannot start with a number
my-name = "Bob"   # No hyphens (use underscores)
class = "Math"    # 'class' is a reserved keyword

The Python convention is snake_case — lowercase words separated by underscores: first_name, total_price, is_active. Not firstName or TotalPrice.

⚡

Label the Boxes

25 XP
Create variables for the following real-world data. Write the Python code: 1. Your first name (text) 2. Your age (whole number) 3. Your height in meters (decimal number) 4. Whether you have a pet (true or false) Example: ```python first_name = "Your Name" age = ___ height_meters = ___ has_pet = ___ ``` Run your code. Then add `print(first_name, age, height_meters, has_pet)` and check the output. _Hint: Text goes in quotes. Numbers do not. True/False are capitalized in Python: `True`, `False`._

The four core data types

Every piece of data in Python has a type. Think of types as the material the box is made of — a glass jar for liquids, a cardboard box for solids, a folder for documents. The type determines what you can do with the data.

TypeWhat it storesExampleReal-world analogy
str (string)Text"Hello", 'Python'A sticky note with words on it
int (integer)Whole numbers42, -7, 0Counting on your fingers
float (floating-point)Decimal numbers3.14, -0.5, 98.6A thermometer reading
bool (boolean)True or FalseTrue, FalseA light switch — on or off

You can check any value's type with type():

print(type("Hello"))      # <class 'str'>
print(type(42))            # <class 'int'>
print(type(3.14))          # <class 'float'>
print(type(True))          # <class 'bool'>

Strings — text data

Strings are text wrapped in quotes. Single quotes or double quotes both work — just be consistent:

greeting = "Hello, World!"
name = 'Alice'
paragraph = """This is a
multi-line string. Use triple
quotes for multiple lines."""

Useful string operations:

first = "John"
last = "Doe"

full_name = first + " " + last    # Concatenation: "John Doe"
shouting = full_name.upper()       # "JOHN DOE"
whisper = full_name.lower()        # "john doe"
length = len(full_name)            # 8 (counts characters including space)
🔑f-strings are your best friend
Instead of clunky concatenation, use **f-strings** (formatted strings). Put an `f` before the quote and wrap variables in curly braces:
name = "Sarah"
age = 28
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Sarah and I am 28 years old.

This is how professional Python developers write string output. It is cleaner, faster, and less error-prone than + concatenation.

Numbers — integers and floats

# Integers — whole numbers
population = 8000000000
negative = -42
zero = 0

# Floats — decimal numbers
pi = 3.14159
price = 19.99
temperature = -40.0

# Arithmetic
print(10 + 3)      # 13 (addition)
print(10 - 3)      # 7 (subtraction)
print(10 * 3)      # 30 (multiplication)
print(10 / 3)      # 3.3333... (division — always returns float)
print(10 // 3)     # 3 (floor division — rounds down)
print(10 % 3)      # 1 (modulo — remainder)
print(10 ** 3)     # 1000 (exponentiation — 10 to the power of 3)

✗ Without AI

  • ✗10 // 3 = 3
  • ✗7 // 2 = 3
  • ✗Always returns a whole number
  • ✗Drops the decimal part

✓ With AI

  • ✓10 / 3 = 3.333...
  • ✓7 / 2 = 3.5
  • ✓Always returns a float
  • ✓Keeps the decimal part

Booleans — true or false

Booleans are the simplest type — only two possible values: True or False. They are named after George Boole, the mathematician who invented Boolean algebra.

is_raining = True
has_umbrella = False
should_go_outside = not is_raining  # False

# Comparison operators return booleans
print(5 > 3)       # True
print(5 == 3)      # False
print(5 != 3)      # True (not equal)
print(5 >= 5)      # True (greater than or equal)

There Are No Dumb Questions

"Why does Python have both int and float? Why not just one number type?"

Integers are exact. 10 is always exactly 10. Floats are approximations — 0.1 + 0.2 in Python equals 0.30000000000000004, not 0.3. This is not a Python bug; it is how all computers store decimal numbers (IEEE 754 floating-point). For counting things (users, items, loops), use integers. For measuring things (temperature, price, distance), use floats. For money, use integers representing cents (1999 instead of 19.99) to avoid rounding errors.

"What happens if I put a number in quotes?"

It becomes a string, not a number. 42 is an integer you can do math with. "42" is text — two characters, a 4 and a 2. Python treats them completely differently. 42 + 8 gives 50. "42" + "8" gives "428" (concatenation, not addition). This is the single most common beginner bug.

Type conversion — changing between types

Sometimes you need to convert data from one type to another. Python gives you built-in functions for this:

# String to integer
age_text = "25"
age_number = int(age_text)     # 25 (now you can do math)

# Integer to string
count = 42
count_text = str(count)        # "42" (now you can concatenate)

# String to float
price_text = "19.99"
price = float(price_text)      # 19.99

# Float to integer (drops decimal, does NOT round)
temperature = 98.6
temp_int = int(temperature)    # 98 (not 99!)

# Boolean conversions
print(bool(0))       # False (zero is falsy)
print(bool(1))       # True (any non-zero number is truthy)
print(bool(""))      # False (empty string is falsy)
print(bool("hello")) # True (non-empty string is truthy)
⚠️int() does not round — it truncates
`int(3.9)` returns `3`, not `4`. It chops off the decimal, always rounding toward zero. If you want proper rounding, use `round(3.9)` which returns `4`. This distinction matters when you are working with financial or scientific data.

⚡

The Input Bug

25 XP
Run this code: ```python age = input("Enter your age: ") next_year = age + 1 print(f"Next year you will be {next_year}") ``` This will crash with a `TypeError`. Why? Fix it so it works correctly. _Hint: The `input()` function ALWAYS returns a string, even if the user types a number. You need to convert it. What function turns a string into an integer?_

There Are No Dumb Questions

"What happens if I try to convert 'hello' to an integer?"

Python raises a ValueError and crashes. int("hello") makes no sense — there is no number in "hello." You can only convert strings that actually contain valid numbers: int("42") works, int("42.5") crashes (use float() first), int("forty-two") crashes. Always validate user input before converting.

"Why do I need to know about types? Can't Python just figure it out?"

Python does figure out the type automatically when you create a variable. But it does NOT automatically convert between types. "5" + 3 crashes because Python refuses to guess whether you want "53" (string concatenation) or 8 (addition). Other languages (like JavaScript) guess — and that guessing causes silent, hard-to-find bugs. Python's strictness is a feature, not a bug.

⚡

Build a Tip Calculator

50 XP
Write a program that: 1. Asks the user for a bill amount (e.g., "45.50") 2. Asks for a tip percentage (e.g., "20") 3. Calculates the tip amount and total 4. Prints a formatted result Expected output: ``` Bill: $45.50 Tip (20%): $9.10 Total: $54.60 ``` Starter code: ```python bill = float(input("Enter the bill amount: $")) tip_percent = float(input("Enter tip percentage: ")) # Calculate tip and total here # Print the formatted result using f-strings ``` _Hint: Tip = bill * (tip_percent / 100). Use `f"{value:.2f}"` to format numbers to 2 decimal places._

Key takeaways

  • Variables are labeled boxes — a name attached to a value using = (assignment, not equality)
  • Four core types: str (text), int (whole numbers), float (decimals), bool (True/False)
  • f-strings are the modern way to embed variables in text: f"Hello, {name}!"
  • input() always returns a string — convert with int() or float() before doing math
  • int() truncates, it does not round — int(3.9) is 3, not 4
  • "42" is not the same as 42 — one is text, the other is a number; Python will not guess which you want
  • Use snake_case for variable names: first_name, not firstName

?

Knowledge Check

1.What will `print(type("42"))` output?

2.What is the result of `int(7.9)`?

3.What does `"Hello" + " " + "World"` produce?

4.Why does `age = input('Enter age: ')` followed by `age + 1` cause a TypeError?

Previous

Why Python

Next

Control Flow