Learn about variables, math operators, if/elif/else conditions, and logical operators.
In any RPG, your character has stats: health points, attack power, level, gold coins. These numbers change constantly, you gain experience, lose health in battle, buy a new sword. Well, in programming we do exactly the same thing, except we use variables to keep track of all these values.
In this lesson you will learn how to create variables, do calculations with them, and write code that makes decisions, just like a game decides whether your attack hits or whether you have enough gold to buy armor. By the end of the lesson, you will be able to build the basic logic of a mini RPG.
Get ready to create your first character in code. Let's begin!
Your hero from the Python Kingdom needs stats: health points, attack, defense, gold. In this lesson you will build the character sheet for your RPG game. You will use variables to store the hero's stats, if/elif/else to implement class selection, and a shop where the hero can buy equipment.
A variable is like a box with a label on it. You put a value inside and give it a name so you can find it later. In Python, you create a variable simply by writing its name, the = sign, and the value you want to store.
In the example above we created 5 variables. Each has a different data type:
"Aldric" is a string (str), meaning text, always between quotes120 and 350 are integers (int), numbers without decimals7 is also an intTrue is a boolean (bool), can only be True or FalseThere are also decimal numbers, called float:
To see what you stored in a variable, you use the print() function:
You can also display multiple things on the same line, separated by commas:
An important thing: variable values can change. That is why they are called "variables". If your hero takes damage, you subtract from their HP:
In RPGs everything is based on calculations: how much damage you deal, how many coins you have left after buying something, how much experience you need until the next level-up. Python gives you all the operators you need.
Here are the basic math operators:
| Operator | What it does | Example | Result |
|---|---|---|---|
+ | Addition | 80 + 25 | 105 |
- | Subtraction | 120 - 45 | 75 |
* | Multiplication | 15 * 3 | 45 |
/ | Division | 100 / 3 | 33.333... |
// | Floor division | 100 // 3 | 33 |
% | Remainder (modulo) | 100 % 3 | 1 |
Let's see some practical examples with an RPG theme:
Now let's see the more special operators, floor division (//) and modulo (%):
// tells you how many times 12 fits into 50 (4 times), and % tells you how much is left over (2 coins).
Up until now, our code ran line by line, top to bottom, without "thinking". But in a game you need decisions: if HP reaches 0, the character dies; if you have enough gold, you can buy a weapon; if you are level 10, you unlock a new ability.
This is where conditions come in. The basic structure looks like this:
If we also want to handle the case where the player is alive, we add else:
When you have multiple options, you use elif (short for "else if"):
Python checks conditions from top to bottom. The first condition that is true gets executed, and the rest are ignored. If none are true, the else block runs.
You may have noticed that after if, elif, and else, the code that belongs to that block is shifted to the right by 4 spaces. This is called indentation and it is mandatory in Python.
Both print lines are indented by 4 spaces. This means they both belong to the if block. If you remove the spaces, Python will throw an error:
Other programming languages use curly braces {} to mark code blocks. Python uses indentation, which makes code cleaner and easier to read. But you must be consistent, either use 4 spaces or a tab, but do not mix them.
Sometimes a single condition is not enough. Maybe you want to check if the player has both a high enough level and enough gold. Or maybe you want to check if they have either a shield or armor. That is what logical operators are for.
Both conditions are true (8 >= 5 and 200 >= 150), so the success message is displayed.
Even though you do not have a shield, you have armor, and that is enough when using or.
not False becomes True, so the first block runs.
You can combine multiple logical operators in a single condition:
This is one of the most common confusions for beginners, so let's clear it up once and for all.
A single = means assignment, you give a value to a variable:
Two equals == means comparison, you check if two values are equal:
If you accidentally write = instead of == in an if, Python will give you an error. Remember: one equal sets, two equals asks.
Variables store data, operators do calculations, and conditions make decisions. With these three tools you can build the logic of any game. Remember: one equal (=) sets a value, two equals (==) compares values.
Create the variables for the hero of the Python Kingdom game: hero_name (string), hero_class (string), hp (int), attack (int), defense (int), and gold (int). Choose the initial values (for example: "Aldric", "Warrior", 100, 15, 10, 50). Then display the hero sheet with all the stats, each on its own line.
SET hero_name = "Aldric"
SET hero_class = "Warrior"
SET hp = 100
SET attack = 15
SET defense = 10
SET gold = 50
DISPLAY "--- Hero Sheet ---"
DISPLAY "Name: " + hero_name
DISPLAY "Class: " + hero_class
DISPLAY "HP: " + hp
DISPLAY "Attack: " + attack
DISPLAY "Defense: " + defense
DISPLAY "Gold: " + goldThe hero can be a Warrior, Mage, or Archer. Create a variable hero_class with one of these values. Then use if/elif/else to apply different bonuses:
Start with the base values: hp=100, attack=15, defense=10. After applying the bonuses, display the new stats.
SET hero_class = "Warrior"
SET hp = 100, attack = 15, defense = 10
IF hero_class == "Warrior":
hp = hp + 20
attack = attack + 5
DISPLAY "Warrior class! +20 HP, +5 attack"
ELSE IF hero_class == "Mage":
hp = hp + 5
attack = attack + 10
DISPLAY "Mage class! +5 HP, +10 attack"
ELSE IF hero_class == "Archer":
attack = attack + 7
defense = defense + 5
DISPLAY "Archer class! +7 attack, +5 defense"
DISPLAY "HP: " + hp + " | Attack: " + attack + " | Defense: " + defenseThe hero has 50 gold and enters the shop. Create two variables: sword_price = 30 and shield_price = 25. The hero wants to buy the sword. Check if they have enough gold. If yes, subtract the price from gold, add +8 to attack, and display a success message with the remaining gold. If not, display how much gold is missing. Then check if they can also buy the shield with the remaining gold.
SET gold = 50, attack = 20
SET sword_price = 30, shield_price = 25
DISPLAY "--- Kingdom Shop ---"
IF gold >= sword_price:
gold = gold - sword_price
attack = attack + 8
DISPLAY "You bought the Iron Sword! +8 attack"
DISPLAY "Gold remaining: " + gold
ELSE:
DISPLAY "Not enough gold! You are missing " + (sword_price - gold)
IF gold >= shield_price:
DISPLAY "You can also buy the shield!"
ELSE:
DISPLAY "Not enough gold left for the shield."Simulate a hero's attack on a monster. The hero has attack = 23 and the monster has monster_hp = 40 and monster_defense = 5. Calculate the damage: damage = attack - monster_defense. If the damage is greater than 20, it is a critical hit and the damage is doubled. Apply the damage to the monster's HP and display whether the monster was defeated or how much HP it has left.
SET attack = 23, monster_hp = 40, monster_defense = 5
SET damage = attack - monster_defense
IF damage > 20:
damage = damage * 2
DISPLAY "CRITICAL HIT!"
DISPLAY "Damage: " + damage
monster_hp = monster_hp - damage
IF monster_hp <= 0:
DISPLAY "The monster has been defeated!"
ELSE:
DISPLAY "The monster has " + monster_hp + " HP left"You have a squad of 3 warriors. The first deals 22 damage per hit, the second deals 18, and the third deals 31. Calculate the total damage of the squad and display it. Then calculate and display the average damage per warrior (with decimals).
SET warrior_1 = 22, warrior_2 = 18, warrior_3 = 31
SET total = warrior_1 + warrior_2 + warrior_3
SET average = total / 3
DISPLAY "Total squad damage: " + total
DISPLAY "Average damage per warrior: " + averageWrite a program that determines a player's rank based on their score. Create a variable player_score with a value of your choice and display the rank according to these rules:
Test the program with several different values.
SET player_score = 720
IF player_score >= 1000:
DISPLAY "Your rank: Legendary"
ELSE IF player_score >= 500:
DISPLAY "Your rank: Veteran"
ELSE IF player_score >= 100:
DISPLAY "Your rank: Adventurer"
ELSE:
DISPLAY "Your rank: Beginner"Here is your game so far! Now you have the title screen and character creation with class selection and a shop:
Check how well you understood the lesson with these 6 questions.