Chapter 2: Variables and Numbers 🔢
In Chapter 1, you learned to make Python “speak” using print(). But what if you want Python to remember things? That’s where variables come in — they’re like containers that store information for you.
Variables: Your Data Storage Boxes 📦
Imagine you have a box where you can put things and label it. Whenever you need what’s inside, you just look at the label. That’s exactly what a variable does in Python!
A variable is a name that stores a value. Here’s how you create one:
age = 12
name = "Alex"
favorite_color = "blue"
Let’s break this down:
ageis the variable name (the label on your box)=is the assignment operator (it means “store this value”)12is the value being stored
Variable Naming Rules
You can name variables almost anything, but there are a few rules:
✅ Good variable names:
player_score = 100
first_name = "Jordan"
level_2_complete = True
❌ Invalid variable names:
2nd_place = "Silver" # Can't start with a number
my-score = 50 # Can't use hyphens
class = "Math" # Can't use Python keywords
Pro Tips:
- Use descriptive names:
player_healthis better thanph - Use lowercase with underscores:
high_scorenothighscoreorHighScore - Make it meaningful: someone reading your code should understand what the variable stores
Using Variables
Once you create a variable, you can use it anywhere in your program:
username = "CodeMaster"
print("Welcome back,")
print(username)
This prints:
Welcome back,
CodeMaster
You can even use variables inside other print statements:
score = 450
print("Your score is:")
print(score)
Updating Variables: Things Change! 🔄
Variables aren’t set in stone — you can change their values whenever you want. That’s why they’re called “variables” (things that vary)!
points = 10
print(points) # Shows: 10
points = 25
print(points) # Shows: 25
This is super useful in games. Imagine collecting coins:
coins = 0
print("Starting coins:", coins)
# Player collects 5 coins
coins = 5
print("After level 1:", coins)
# Player collects 3 more coins
coins = 8
print("After level 2:", coins)
A Clever Trick: Updating Based on Current Value
You can update a variable based on its current value:
score = 100
score = score + 50 # Take current score, add 50, store the result
print(score) # Shows: 150
Think of it like this: “Take what’s in the box, modify it, then put the new value back in the box.”
Python has a shortcut for this:
score = 100
score += 50 # Same as: score = score + 50
print(score) # Shows: 150
Other shortcuts:
lives = 3
lives -= 1 # Subtract 1 (same as: lives = lives - 1)
print(lives) # Shows: 2
power = 10
power *= 2 # Multiply by 2 (same as: power = power * 2)
print(power) # Shows: 20
Numbers: Integers and Floats 🔢
Python works with two main types of numbers:
1. Integers (Whole Numbers)
Integers are whole numbers without decimal points:
students_in_class = 25
player_level = 7
high_score = 1000
temperature = -5 # Negative numbers work too!
2. Floats (Decimal Numbers)
Floats are numbers with decimal points:
price = 19.99
temperature = 98.6
pi = 3.14159
average_score = 87.5
The name “float” comes from “floating-point number” — a technical term for how computers store decimals.
Why Does It Matter?
Understanding the difference helps you choose the right type:
# Counting things? Use integers
apples = 5
# Measuring things? Use floats
height_in_meters = 1.65
You can check a number’s type:
print(type(42)) # Shows: <class 'int'>
print(type(3.14)) # Shows: <class 'float'>
Math Operations: Python as Your Calculator ➕
Python can do math! Let’s explore the basic operations.
Basic Operations
# Addition
total = 10 + 5
print(total) # Shows: 15
# Subtraction
difference = 20 - 7
print(difference) # Shows: 13
# Multiplication
product = 6 * 4
print(product) # Shows: 24
# Division (always gives a float)
result = 15 / 3
print(result) # Shows: 5.0
Notice that division always gives you a float, even if the answer is a whole number!
Using Variables in Math
apples = 10
oranges = 15
total_fruit = apples + oranges
print("Total fruit:", total_fruit) # Shows: Total fruit: 25
You can combine as many operations as you need:
price_per_item = 5
quantity = 3
tax = 2
total_cost = (price_per_item * quantity) + tax
print("Total cost:", total_cost) # Shows: Total cost: 17
Order of Operations
Python follows the same math rules you learned in school (PEMDAS/BODMAS):
result = 2 + 3 * 4
print(result) # Shows: 14 (not 20, because multiplication happens first)
result = (2 + 3) * 4
print(result) # Shows: 20 (parentheses force addition first)
Remember: When in doubt, use parentheses to make your intentions clear!
More Math: Advanced Operations 🎯
Python has a few special math operators that are super handy.
Exponents (Power)
Use ** to raise a number to a power:
squared = 5 ** 2 # 5 to the power of 2
print(squared) # Shows: 25
cubed = 2 ** 3 # 2 to the power of 3
print(cubed) # Shows: 8
square_root = 16 ** 0.5 # Square root of 16
print(square_root) # Shows: 4.0
Floor Division (Integer Division)
Regular division (/) gives you a float. But what if you only want the whole number part? Use //:
result = 17 / 5
print(result) # Shows: 3.4
result = 17 // 5
print(result) # Shows: 3 (just the whole number)
Think of it like sharing cookies: if you have 17 cookies and 5 friends, each friend gets 3 whole cookies (with some left over).
Modulus (Remainder)
The % operator gives you the remainder after division:
remainder = 17 % 5
print(remainder) # Shows: 2
Why? Because 17 divided by 5 is 3 with a remainder of 2.
When is this useful?
- Checking if a number is even or odd
- Wrapping numbers around (like in a circular game board)
- Distributing items evenly
# Check if a number is even
number = 8
if number % 2 == 0:
print("Even!") # This runs because 8 % 2 = 0
Quick Recap 🎯
Fantastic work! You’ve learned a lot in this chapter:
✅ Variables store data with meaningful names
✅ Variables can be updated as your program runs
✅ Integers are whole numbers, floats have decimals
✅ Math operations: +, -, *, /
✅ Advanced operations: ** (power), // (floor division), % (remainder)
You now have the tools to make Python remember things and do calculations!
🚀 Hands-On Exercise: Build a Score Calculator
Time to practice! Create a program that simulates a simple game scoring system.
Your Mission:
- Create a variable called
player_nameand store your name in it - Create a variable
base_scoreand set it to 100 - The player completes a challenge and earns 50 bonus points — update the score
- The player uses a power-up that doubles the score — update it again
- The player loses 25 points for a mistake — update once more
- Print the player’s name and final score
- Bonus: Calculate and print how many complete sets of 100 points the player has (use
//) - Extra Bonus: Calculate and print the leftover points after removing complete hundreds (use
%)
Example Solution:
# Game Score Calculator
# Player information
player_name = "SkyWalker"
base_score = 100
print("Player:", player_name)
print("Starting score:", base_score)
# Earned bonus points for completing a challenge
base_score += 50
print("After challenge:", base_score)
# Used a power-up to double the score
base_score *= 2
print("After power-up:", base_score)
# Lost points for a mistake
base_score -= 25
print("After mistake:", base_score)
# Final results
print("\n--- Final Results ---")
print("Player:", player_name)
print("Final Score:", base_score)
# Bonus calculations
hundreds = base_score // 100
leftover = base_score % 100
print("Complete hundreds:", hundreds)
print("Leftover points:", leftover)
Challenge Yourself:
- Add more scoring events (found treasure, defeated enemy, etc.)
- Calculate an average score if the player played multiple rounds
- Use exponents to calculate an “achievement multiplier” (like
level ** 2)
Remember: Programming is about experimenting. Try different numbers, add your own twists, and see what happens!
What’s Next? 💭
In the next chapter, you’ll learn how to work with text (strings) in more depth — combining words, formatting messages, and making your programs even more interactive!
Keep experimenting, keep learning! You’re building real programming skills.