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.
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.
| 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 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 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)
✗ 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
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 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 XPKey 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
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?