Victor Jeman - Frontend Architectv3.0
Python Fundamentals15 min

Variables, calculations and decisions

Learn about variables, math operators, if/elif/else conditions, and logical operators.

What You'll Learn

  • Understand what variables are and how to use them to store data
  • Use math operators for calculations
  • Write if/elif/else conditions to make decisions in your program
  • Combine conditions using the logical operators and, or, not

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.

Variables

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 quotes
  • 120 and 350 are integers (int), numbers without decimals
  • 7 is also an int
  • True is a boolean (bool), can only be True or False

There 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:

Math operators

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:

OperatorWhat it doesExampleResult
+Addition80 + 25105
-Subtraction120 - 4575
*Multiplication15 * 345
/Division100 / 333.333...
//Floor division100 // 333
%Remainder (modulo)100 % 31

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).

Conditions (if / elif / else)

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.

Indentation

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.

Logical operators (and, or, not)

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.

and - both conditions must be true

Both conditions are true (8 >= 5 and 200 >= 150), so the success message is displayed.

or - at least one condition must be true

Even though you do not have a shield, you have armor, and that is enough when using or.

not - reverses a condition

not False becomes True, so the first block runs.

You can combine multiple logical operators in a single condition:

The difference between = and ==

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.

Exercise : Hero Sheet from the Python Kingdom

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.

Exercise : Hero class selection

The 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:

  • Warrior: +20 HP, +5 attack
  • Mage: +5 HP, +10 attack
  • Archer: +7 attack, +5 defense

Start with the base values: hp=100, attack=15, defense=10. After applying the bonuses, display the new stats.

Exercise : Kingdom Shop

The 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.

Exercise : Attack with critical hit

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.

Exercise : Team average damage

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).

Exercise : Rank system

Write 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:

  • Score >= 1000: rank "Legendary"
  • Score >= 500: rank "Veteran"
  • Score >= 100: rank "Adventurer"
  • Score below 100: rank "Beginner"

Test the program with several different values.

Complete game code: Python Kingdom (Lesson 2)

Here is your game so far! Now you have the title screen and character creation with class selection and a shop:

Test Your Knowledge

Check how well you understood the lesson with these 6 questions.

Question 1 of 6

What data type is the value 3.14?