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. In Module 1, you wrote print("Hello, World!") — you told Python what to display, but the data disappeared the instant the program ended. Variables let you hold onto data so you can use it again and again. These are the building blocks of every program you will ever write.
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.6That is it. No special keywords, no type declarations. Python figures out the type automatically.
| Concept | Real-world analogy | Python example |
|---|---|---|
| Variable name | The label on the box | age, name, price |
| Value | What is inside the box | 25, "Sarah", 19.99 |
Assignment (=) | Taping the label onto the box | age = 25 |
| Reassignment | Replacing the contents | age = 26 |
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 keywordThe Python convention is snake_case — lowercase words separated by underscores: first_name, total_price, is_active. Not firstName or TotalPrice.
Label the Boxes
25 XPCreate 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`._
Sign in to earn XPThe 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.
| Type | What it stores | Example | Real-world analogy |
|---|---|---|---|
str (string) | Text | "Hello", 'Python' | A sticky note with words on it |
int (integer) | Whole numbers | 42, -7, 0 | Counting on your fingers |
float (floating-point) | Decimal numbers | 3.14, -0.5, 98.6 | A thermometer reading |
bool (boolean) | True or False | True, False | A 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)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)✗ Integer division (//)
- ✗10 // 3 = 3
- ✗7 // 2 = 3
- ✗Always returns a whole number
- ✗Drops the decimal part
✓ Regular division (/)
- ✓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)<classifychallenge xp="25" title="Name That Type" items={[""Hello, World!"","42","3.14","True",""99"","0","-17.5","False"]} options={["str","int","float","bool"]} hint="Anything in quotes is a string — even "99" is text, not a number. Whole numbers without quotes are int. Numbers with a decimal point are float. True and False (capitalized, no quotes) are bool.">
There Are No Dumb Questions
"Why does Python have both
intandfloat? Why not just one number type?"Integers are exact.
10is always exactly10. Floats are approximations —0.1 + 0.2in Python equals0.30000000000000004, not0.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 (1999instead of19.99) to avoid rounding errors."What happens if I put a number in quotes?"
It becomes a string, not a number.
42is an integer you can do math with."42"is text — two characters, a4and a2. Python treats them completely differently.42 + 8gives50."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)The Input Bug
25 XPRun 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?_
Sign in to earn XPThere Are No Dumb Questions
"What happens if I try to convert 'hello' to an integer?"
Python raises a
ValueErrorand 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 (usefloat()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" + 3crashes because Python refuses to guess whether you want"53"(string concatenation) or8(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 XPWrite 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._
Sign in to earn XPBack to the hospital spreadsheet
Those 16,000 lost COVID test results happened because the team did not understand data types. The .xls format had a hard limit on integers in a column — and nobody checked. In Python, you would never hit that wall. A Python list can hold millions of rows. A Python integer can be arbitrarily large. And type() lets you check what you are working with at any point.
Data types are not abstract theory. They are the difference between a working system and a system that silently loses 16,000 lives.
Next up: You now know how to store data. But a program that just stores data is a spreadsheet. In the next module, you will learn control flow — how to make your program think. If the score is above 90, print "A." Loop through every item in a list. Keep asking until the user gets the password right. That is where programming gets powerful.
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 withint()orfloat()before doing mathint()truncates, it does not round —int(3.9)is3, not4"42"is not the same as42— one is text, the other is a number; Python will not guess which you want- Use
snake_casefor variable names:first_name, notfirstName
Try it yourself
Experiment with variables and data types in this live Python playground:
Now prove you can write it yourself. Complete both test cases:
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?
Want to go deeper?
💻 Software Engineering Master Class
The complete software engineering program — from your first line of code to landing your first job.
View the full program