Lesson 2 • Beginner
Variables and Data Types
Learn how to store, name, and work with different types of data in Python — the foundation of every program.
What You'll Learn in This Lesson
- ✓What a variable is and why every program needs them
- ✓The 4 core data types: str, int, float, bool
- ✓Python's strict rules for naming variables
- ✓How to update variables using shorthand operators
- ✓3 ways to print variables (comma, +, f-string)
- ✓How to check a variable's type with type()
1What Is a Variable?
A variable is a named container that stores a value in your computer's memory.
🎁 Think of it like a labeled box:
- The label is the variable name (like "age" or "name")
- The contents are the value you put inside (like 25 or "Alice")
- You can peek inside the box anytime to see what's there
- You can swap out the contents whenever you want
In plain English:
name = "Alice" # Create a box labeled 'name', put "Alice" inside age = 25 # Create a box labeled 'age', put 25 inside
When Python sees name = "Alice", it:
- Creates a spot in memory
- Labels it "name"
- Stores the text "Alice" there
2Why Do Variables Matter?
Without variables, your program would be stuck. It couldn't:
- Remember a user's name after they type it
- Keep track of a game score
- Store prices in a shopping cart
- Save any information between steps
🌍 Variables in Real Programs
Let's look at how variables work together in a real scenario. Here's a simple receipt calculator — the kind of logic that powers every online shop:
# A simple receipt calculator
item_name = "Python Book"
price = 29.99
quantity = 2
discount = 5.00
tax_rate = 0.20
subtotal = price * quantity
after_disc = subtotal - discount
tax_amount = after_disc * tax_rate
total = after_disc + tax_amount
print(f"Item: {item_name}")
print(f"Subtotal: £{subtotal:.2f}")
print(f"Discount: -£{discount:.2f}")
print(f"Tax: £{tax_amount:.2f}")
print(f"TOTAL: £{total:.2f}")Every variable has a clear, descriptive name. You can read this like a sentence. That's the goal of good variable naming.
Readability
Anyone can understand what each variable holds without guessing
Reusability
Change price once at the top — every calculation updates automatically
Maintainability
Add a new tax rate next year by changing one line, not ten
Notice the :.2f inside the f-string — that formats a float to 2 decimal places (like £29.99, not £29.990000). You'll learn more formatting tricks as you progress.
3Creating Variables — The Assignment Operator
In Python, you create a variable using the = sign:
user_name = "Boopie" user_age = 16
= sign means "assign" or "store", NOT "equals" like in math! Read it as: "Store 'Boopie' into user_name"You can update variables anytime:
points = 10 # Start with 10 points points = points + 5 # Add 5 more # Now points holds 15 points = 100 # Completely replace with 100 # Now points holds 100
4The 4 Basic Data Types
Every variable stores a type of data. Python has 4 basic types you must know:
📝 Strings (str)
Text — must be inside quotes
name = "Alice" city = 'New York' empty = ""
⚠️ Even "123" is a string if it's in quotes!
🔢 Integers (int)
Whole numbers — no decimal point
age = 25 year = 2024 negative = -10
✓ You can do math with integers
💰 Floats (float)
Decimal numbers — has a decimal point
price = 19.99 pi = 3.14159 temp = -2.5
✓ Use for prices, measurements, percentages
✅ Booleans (bool)
True or False — exactly two options
is_student = True has_license = False
⚠️ Capital T and F! true won't work.
📝 Deep Dive: Strings
Strings are the most common data type in real programs — almost every app deals with text. Here's everything you need to know at this stage.
String methods — built-in actions you can call on any string
message = " Hello, World! "
print(message.upper()) # " HELLO, WORLD! " — all caps
print(message.lower()) # " hello, world! " — all lowercase
print(message.strip()) # "Hello, World!" — removes surrounding spaces
print(message.replace("World", "Python")) # " Hello, Python! "
name = "alice"
print(name.capitalize()) # "Alice" — first letter uppercase only
print(name.title()) # "Alice" — title case (good for names)Methods are called using a dot . after the variable name. Python has dozens of string methods — these are the most useful ones to start with.
Multiline strings — triple quotes
Need to store text that spans multiple lines? Use three quotes:
poem = """ Roses are red, Violets are blue, Python is awesome, And so are you! """ print(poem)
Triple quotes preserve all line breaks and indentation exactly as written. Very useful for long messages, templates, or documentation.
Escape characters — special characters inside strings
print("Line 1\nLine 2") # \n = new line
print("Col1\tCol2") # \t = tab (indent)
print("He said \"Hello\"") # \" = literal quote inside stringThe backslash \ tells Python "this next character is special". The most common are \n (new line) and \t (tab).
Checking string length
password = "securePass123"
print(len(password)) # 13
# Useful for validation:
if len(password) >= 8:
print("Password is long enough") # You'll learn 'if' in Lesson 3!len() works on any string. It counts every character — letters, numbers, spaces, and symbols.
.replace() and other methods always return a new string rather than modifying the original. To "update" a string, reassign the variable: name = name.upper()🔢 Deep Dive: Numbers (int and float)
Numbers seem simple — but there are a few behaviours that surprise beginners every time.
int vs float — when does each appear?
print(10 / 2) # 5.0 ← always float, even though result is whole print(10 // 2) # 5 ← floor division, always int print(10 % 3) # 1 ← remainder (modulo) print(2 ** 10) # 1024 ← exponent (2 to the power of 10)
The regular / operator always returns a float in Python 3, even when dividing 10 by 2. If you need a whole number, use //.
Readable large numbers
Python lets you add underscores to large numbers to make them easier to read — Python ignores them:
salary = 75_000 # Same as 75000 population = 8_000_000_000 # 8 billion distance = 384_400 # Distance to moon (km) print(salary) # 75000 — underscore disappears in output
Useful built-in number functions
print(round(3.7)) # 4 — round to nearest whole print(round(3.14159, 2)) # 3.14 — round to 2 decimal places print(abs(-25)) # 25 — absolute value (remove minus sign) print(max(5, 12, 3)) # 12 — largest value print(min(5, 12, 3)) # 3 — smallest value
These built-in functions work without any imports — Python provides them automatically.
Floating point precision — a known quirk
print(0.1 + 0.2) # 0.30000000000000004 (not 0.3!) print(round(0.1 + 0.2, 2)) # 0.3 ← use round() to fix
This isn't a Python bug — it's how computers store decimal numbers in binary memory. It affects every programming language. The fix is simple: use round() when displaying financial or precise values.
✅ Deep Dive: Booleans
Booleans look simple — just True or False — but they're the most powerful type in programming. Every decision your program makes comes down to a boolean.
Where booleans come from
You'll often get booleans by comparing values. These are called comparison expressions and you'll master them fully in Lesson 3:
age = 18 print(age >= 18) # True — is age 18 or over? print(age == 16) # False — is age exactly 16? print(age != 21) # True — is age NOT 21? name = "Alice" print(name == "Alice") # True print(name == "alice") # False — case sensitive!
Truthy and Falsy — every value has a boolean equivalent
Python can treat any value as True or False. This is called truthiness:
print(bool(0)) # False — zero is always False
print(bool(1)) # True — any non-zero number is True
print(bool(-99)) # True
print(bool("")) # False — empty string is False
print(bool("hello")) # True — any non-empty string is True
print(bool(None)) # FalseYou don't need to memorise all of these now. Just know that the concept exists — it will click naturally when you reach conditional statements.
True and False must start with a capital. true (lowercase) is a NameError — Python doesn't recognise it as a boolean keyword.Try It Yourself: Create Variables
Practice creating variables of each data type
# Create variables of each type
name = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
# Print them out
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)
# Check the type of each variable
print("Type of name:", type(name))
print("Type of age:", type(age))
# 🎯 YOUR TURN: Create your own variables below!
your_name = "___"
your_age = 0
print(f"Hi, I'm {your_name} and I'm {yo
...5Variable Naming Rules (MUST Know)
Python has strict rules for variable names. Break them = error.
Allowed
name— starts with letter ✓_count— starts with underscore ✓user_age_2— letters, numbers, underscores ✓firstName— camelCase works (but snake_case preferred)
NOT Allowed
2name— starts with number ✗user-name— no hyphens ✗my name— no spaces ✗print— Python keyword ✗
💡 Best Practices:
- • Use descriptive names:
total_pricenottp - • Use snake_case: lowercase with underscores (
user_name) - • Names are case-sensitive:
Age≠age≠AGE
📏 Naming Conventions and Constants
Python has community-agreed naming conventions (called PEP 8 style). Following them makes your code immediately readable to every other Python developer on earth.
snake_case — the Python standard
Use lowercase words separated by underscores for all regular variables and function names:
✅ Python style (snake_case)
user_name = "Alice" total_price = 49.99 is_logged_in = True max_retry_count = 3
⚠️ Works but not Python style
userName = "Alice" totalPrice = 49.99 isLoggedIn = True maxRetryCount = 3
camelCase (like the second column) is valid Python but is the convention in other languages like JavaScript and Java. Stick to snake_case in Python.
Constants — ALL_CAPS
A constant is a variable whose value should never change after it's set. Python doesn't enforce this — it's purely a convention to signal intent to other developers:
PI = 3.14159 MAX_SCORE = 100 SITE_NAME = "Learn Code Swiftly" TAX_RATE = 0.20 DB_TIMEOUT = 30
When you see ALL_CAPS, it means: "this value is fixed — don't change it elsewhere in the code." Other developers will immediately understand this convention.
The one-character trap
# Bad — impossible to understand later: x = 25 y = 4.99 z = True # Good — self-documenting: user_age = 25 item_price = 4.99 is_in_stock = True
One-character variable names (x, y, z) are only acceptable in short mathematical formulas. For everything else, use descriptive names. Your future self will thank you.
6Updating Variables
Variables can be changed at any time. The old value is replaced.
favorite_color = "Blue" print(favorite_color) # Output: Blue favorite_color = "Red" print(favorite_color) # Output: Red (Blue is gone!)
Shorthand operators make updating easier:
score = 10 score += 5 # Same as: score = score + 5 → 15 score -= 3 # Same as: score = score - 3 → 12 score *= 2 # Same as: score = score * 2 → 24 score /= 4 # Same as: score = score / 4 → 6.0
🔄 Multiple Assignment and Swapping
Python has some elegant shortcuts for assigning and rearranging variables that you'll use constantly.
Assign multiple variables in one line
# Instead of three separate lines: x = 5 y = 10 z = 15 # You can write one line: x, y, z = 5, 10, 15 # Check they worked: print(x, y, z) # 5 10 15
The number of variables on the left must exactly match the number of values on the right — otherwise Python raises a ValueError.
Assign the same value to multiple variables
# Set multiple counters to zero at once: lives = score = level = 0 print(lives, score, level) # 0 0 0 # Useful for initialising several related variables: red = green = blue = 255
Swapping two variables — Python's elegant trick
In most languages, swapping two variables requires a temporary "placeholder" variable. Python doesn't:
Other languages (needs a temp):
a = 5 b = 10 temp = a # save a a = b # overwrite a b = temp # restore old a
Python (one clean line):
a = 5 b = 10 a, b = b, a # swap! print(a, b) # 10 5
This works because Python evaluates the entire right side first, then assigns. It's one of the small reasons developers enjoy writing Python.
7Printing Variables (3 Ways)
There are multiple ways to display variables:
Method 1: Comma separation
name = "Alice" age = 25 print(name, "is", age, "years old.") # Output: Alice is 25 years old.
Python adds spaces automatically between items.
Method 2: String concatenation (+ operator)
name = "Alice" age = 25 print(name + " is " + str(age) + " years old.") # Output: Alice is 25 years old.
⚠️ Must convert numbers to string with str()!
✨ Method 3: f-strings (BEST — Modern Python)
name = "Alice"
age = 25
print(f"{name} is {age} years old.")
# Output: Alice is 25 years old.Start with f, put variables in {} — cleanest option!
8Type Conversion (Changing Types)
Sometimes you need to convert one type to another:
# String to number
age_text = "25"
age = int(age_text) # Now it's an integer: 25
price = float("19.99") # Now it's a float: 19.99
# Number to string
age = 25
age_text = str(age) # Now it's text: "25"
# Check the type
print(type(age)) # <class 'int'>
print(type(age_text)) # <class 'str'>input() function always returns text (string). To do math with user input, convert it: age = int(input("Age: "))🔁 Type Conversion: The Full Picture
Type conversion looks simple — but there are important edge cases that will catch you out if you're not aware of them.
What works and what doesn't
# ✅ These work:
int("42") # → 42 (text digits → integer)
float("3.14") # → 3.14 (text decimal → float)
str(100) # → "100" (number → text)
bool(0) # → False
bool("hello") # → True
# ❌ These FAIL with a ValueError:
int("3.14") # ERROR — can't convert decimal string to int directly
int("hello") # ERROR — not a number at all
float("abc") # ERRORThe two-step conversion trick
To convert "3.14" to an integer, you need to go through float first:
text = "3.14" # ❌ This fails: result = int(text) # ValueError! # ✅ This works — convert to float first, then to int: result = int(float(text)) # → 3 (decimal is dropped, not rounded)
Notice: int() truncates (drops the decimal) rather than rounding. int(3.9) gives 3, not 4.
Full conversion reference
| Function | Converts to | Example | Result |
|---|---|---|---|
int() | Integer | int("42") | 42 |
float() | Float | float("3.14") | 3.14 |
str() | String | str(100) | "100" |
bool() | Boolean | bool(0) | False |
int(float()) | Int from decimal string | int(float("3.9")) | 3 |
int(input(...)), your program crashes with a ValueError. In a later lesson you'll learn how to handle this gracefully with try/except.9Common Errors (And How to Fix Them)
Errors are normal! Here's what you'll see most often:
❌ TypeError
Happens when you mix types incorrectly:
age = 25
print("Age: " + age) # ❌ Can't add string + number✅ Fix: Convert with str() or use f-string:
print("Age: " + str(age)) # ✅ Works
print(f"Age: {age}") # ✅ Even better❌ NameError
Using a variable that doesn't exist:
print(username) # ❌ 'username' was never created
✅ Fix: Create the variable first:
username = "Alice" print(username) # ✅ Now it exists
Also check for typos: usernme ≠ username
❌ SyntaxError
Code is written incorrectly:
name = "Alice # ❌ Missing closing quote
print("Hello" # ❌ Missing closing parenthesis✅ Fix: Check quotes and brackets match:
name = "Alice"
print("Hello")Try It: Practical Examples
Practice with profile cards, updating values, and swapping
# Profile Card Practice
name = "Boopie"
age = 16
favorite_color = "Green"
likes_coding = True
print("=== My Profile ===")
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Favorite Color: {favorite_color}")
print(f"Likes Coding: {likes_coding}")
# Updating values
print("\n=== After Birthday ===")
age += 1 # Happy birthday!
print(f"New age: {age}")
# Swapping two variables
print("\n=== Swap Example ===")
a = 5
b = 10
print(f"Before swap: a = {a}, b = {b}")
a, b = b, a # Python's elegant sw
...Real-World Example: Student Grade Tracker
Let's put everything from this lesson together into one real program. Read it line by line — every concept here is something you've learned in Lessons 1 and 2.
# === Student Grade Tracker ===
# Student information (strings + int)
student_name = "Jamie Chen"
student_id = "S20241042"
year_group = 11
# Subject scores (integers, 0-100)
maths_score = 78
english_score = 85
science_score = 91
history_score = 72
# Calculate average (float division)
total_marks = maths_score + english_score + science_score + history_score
average = total_marks / 4
average = round(average, 1) # Round to 1 decimal place
# Determine pass/fail (boolean)
PASS_MARK = 60 # Constant — never changes
is_passing = average >= PASS_MARK
# Assign grade letter
if average >= 90:
grade = "A"
elif average >= 75:
grade = "B"
elif average >= 60:
grade = "C"
else:
grade = "F"
# Display the report card
print("=" * 35)
print(f" STUDENT REPORT — {student_name}")
print("=" * 35)
print(f"Student ID: {student_id}")
print(f"Year Group: {year_group}")
print()
print(f"Maths: {maths_score}/100")
print(f"English: {english_score}/100")
print(f"Science: {science_score}/100")
print(f"History: {history_score}/100")
print()
print(f"Average: {average}/100")
print(f"Grade: {grade}")
print(f"Status: {'PASSING ✓' if is_passing else 'NEEDS IMPROVEMENT'}")
print("=" * 35)Variables used
str, int, float, bool — all 4 types
Constant
PASS_MARK = 60 (ALL_CAPS convention)
Arithmetic
total, average, round()
f-strings
every line of the report card
Boolean
is_passing — True/False decision
String method
* 35 to draw separator lines
Notice the if/elif/else block
You haven't formally learned this yet — that's Lesson 3. But you can probably guess what it does just from reading it. That's Python's readability at work. By the end of Lesson 3 you'll write exactly this kind of logic yourself.
📋 Quick Reference
| Concept | What It Is | Example |
|---|---|---|
| Variable | Named container for data | x = 10 |
| String (str) | Text in quotes | "Hello" |
| Integer (int) | Whole number | 25 |
| Float | Decimal number | 3.14 |
| Boolean (bool) | True or False | True |
| f-string | Insert variables in text | f"Hi {name}" |
| type() | Check data type | type(x) |
❓ Frequently Asked Questions
Q: What is a variable in Python?
A: A named storage location that holds data your program can use or change later.
Q: What are the 4 main data types?
A: Strings (text), Integers (whole numbers), Floats (decimals), Booleans (True/False).
Q: Can variable names start with numbers?
A: No — they must start with a letter or underscore.
Q: Why do I get "TypeError: can only concatenate str..."?
A: You're trying to combine text + number. Use str() to convert, or use an f-string.
Q: What's the best way to print variables?
A: f-strings! They're cleaner and don't require type conversion: f"Age: {age}"
🎯 Mini Challenge: About Me Program
Create a program that introduces yourself:
- Create variables for: name (string), age (int), favorite color (string), likes_coding (bool)
- Print all four with nice labels
- Update your age (birthday!) and print the new value
Mini Challenge
Create your own introduction program
# 🎯 YOUR TURN: Fill in your details!
name = "Your Name"
age = 0
favorite_color = "Your Color"
likes_coding = True
# Print your profile
print("=== About Me ===")
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Favorite Color: {favorite_color}")
print(f"Likes Coding: {likes_coding}")
# Update age (it's your birthday!)
age += 1
print(f"\nAfter my birthday, I'm now {age}!")Lesson 2 complete — you now speak Python's data language!
You can create variables, work with all 4 core data types, update values with shorthand operators, and print output three different ways. Every single Python program ever written uses exactly these skills.
🚀 Up next: Operators & Expressions — learn how to do math, compare values, and combine conditions in Python.
Sign up for free to track which lessons you've completed and get learning reminders.