Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 2

Conditional Logic: If-Else & Comparison Operators

Recommended resources

Welcome back! In our last lesson, we covered the fundamentals of storing and manipulating data using variables, different data types, and arithmetic operators. You learned how to get input from a player and perform basic calculations—the first essential skills for any game programmer.

This lesson builds directly on that foundation. A game wouldn't be very interesting if it did the same thing every time. We need our programs to make decisions and react to different situations. This is where we introduce the concept of control flow. Your goal for this lesson is to learn how to control your program's flow using if-else statements and comparison operators.

By the end of this lesson, you'll be able to write code that can:

  • Check if a player has enough gold to buy an item.
  • Determine if a character's health has dropped to zero.
  • React differently based on player choices.

These are the building blocks of virtually every mechanic in the RPGs you want to create.

Making Decisions with if

Think of your program as a path. So far, it's been a straight line from start to finish. An if statement creates a fork in that path. It checks if a specific condition is true, and if it is, it executes a block of code. If the condition is false, the code block is skipped.

The basic structure looks like this:

if condition:
    # This code runs only if the condition is True
    # Notice the indentation!

This is the core of decision-making. To form a condition, we use comparison operators.

Python Comparison Operators Infographic
This chart shows the six main comparison operators in Python. They allow you to compare two values.

Here are the operators in action:

Operator Name Example (a = 5, b = 10) Result
== Equal to a == 5 True
!= Not equal to a != 10 True
> Greater than b > a True
< Less than a < b False
>= Greater than or equal to a >= 5 True
<= Less than or equal to b <= a False

Crucial Point: A very common mistake for beginners is confusing the assignment operator (=) with the comparison operator (==).

  • player_health = 100 sets the player's health to 100.
  • player_health == 100 checks if the player's health is 100.

The video below gives a great walkthrough of how to structure if, elif, and else statements.

If statements in Python are easy (if, elif, else) 🤔

Watch this video from Bro Code for a clear, step-by-step explanation of if-statements. It will cover the basic syntax and provide simple examples.

Watch from the beginning to 01:37. Pay close attention to the syntax: the if keyword, the condition, the colon :, and the indented block of code underneath it.


Providing an Alternative with else

What if you want something to happen when the if condition is false? That's what the else statement is for. It provides an alternative path for your program to take.

Let's expand our RPG shop example:

player_gold = 25
potion_cost = 30

if player_gold >= potion_cost:
    print("You bought the healing potion!")
else:
    print("You don't have enough gold.")

In this case, since 25 >= 30 is False, the code inside the else block will run, and the message "You don't have enough gold." will be printed.

Now, continue with the video you started to see how else works in practice.

If statements in Python are easy (if, elif, else) 🤔

This next segment demonstrates how to add an else block to provide a default action when the if condition isn't met.

Watch from 01:37 to 02:21. Notice how the else: line is not indented, and the code within it is.


Handling Multiple Conditions with elif

Sometimes you have more than two possibilities. In an RPG, a character's alignment might not be just "good" or "evil," but also "neutral." For this, we can use elif, which is short for "else if." It lets you check multiple conditions in a sequence.

Python checks each condition from top to bottom:

  1. It checks the if condition first. If it's true, it runs that code and skips the rest.
  2. If the if is false, it moves to the first elif and checks its condition.
  3. It continues down the elif blocks until it finds one that is true.
  4. If none of the if or elif conditions are true, it will run the code in the else block, if one exists.
player_level = 7

if player_level >= 20:
    print("The king addresses you as a Master Adventurer.")
elif player_level >= 10:
    print("The guard captain nods respectfully.")
elif player_level >= 5:
    print("The town blacksmith offers you a discount.")
else:
    print("A child points at your rusty sword and giggles.")

In this example, since player_level is 7, the program would print "The town blacksmith offers you a discount."

Let's finish the video to see how elif completes the structure and how the order of your conditions matters.

If statements in Python are easy (if, elif, else) 🤔

This final segment on if/elif/else explains how to chain multiple checks together and highlights why the order of your conditions is important.

Watch from 02:21 to 04:17. The example of checking age is a great illustration of why you often need to check the most specific conditions first.


Reading and Best Practices

Watching videos is helpful, but reading can solidify your understanding. The following article provides a great summary of what we've covered and introduces some important best practices.

if-else statement in Python

This article from Medium explains conditional logic and its importance, especially in game development. It also covers common mistakes and how to avoid them.

Read the sections 'Purpose of Conditional Logic in Programming', 'Basic Syntax and Structure', and the game development example under 'Real-World Examples'. This will reinforce the syntax and show you a direct application to your goal.

As mentioned in the article, one key best practice is to use logical operators (and, or, not) to combine conditions. This helps you avoid messy, nested if statements.

For example, to check if a player can enter a secret area, you might need them to be a certain level and have a specific key.

# Instead of this (nested):
if player_level >= 15:
    if has_boss_key == True:
        print("You can enter the throne room!")

# You can do this (cleaner):
if player_level >= 15 and has_boss_key == True:
    print("You can enter the throne room!")
Test your understanding!

Imagine you're creating a simple dialogue choice. You meet a grumpy troll guarding a bridge.

Write a Python program that does the following:

  1. Asks the player for their action by printing: "A grumpy troll blocks your path. What do you do? (FIGHT, PAY, or FLEE)".
  2. Stores the player's response in a variable. Remember that input() gives you a string.
  3. Uses an if/elif/else structure to react to the player's choice:
    • If the player types "FIGHT" (or "fight"), it should print: "The troll is too strong! You are knocked unconscious."
    • If the player types "PAY", it should print: "The troll grunts, takes your gold, and lets you pass."
    • If the player types "FLEE", it should print: "You run away, tail between your legs."
    • For any other input, it should print: "The troll stares at you, confused by your actions."

Hint: The .upper() string method can be useful here. For example, action.upper() would turn "fight" into "FIGHT", making your comparison easier.

Show answer

Here is one possible solution:

# 1. Ask the player for their action
print("A grumpy troll blocks your path. What do you do? (FIGHT, PAY, or FLEE)")
action = input("> ")

# 2. Convert input to uppercase to handle 'fight', 'Fight', 'FIGHT', etc.
action = action.upper()

# 3. Use if/elif/else to determine the outcome
if action == "FIGHT":
    print("The troll is too strong! You are knocked unconscious.")
elif action == "PAY":
    print("The troll grunts, takes your gold, and lets you pass.")
elif action == "FLEE":
    print("You run away, tail between your legs.")
else:
    print("The troll stares at you, confused by your actions.")

Conclusion

Fantastic work! You've just learned one of the most powerful concepts in programming. Giving your code the ability to make decisions is the first major step toward creating dynamic and interactive games.

Here are the key takeaways from this lesson:

  • if, elif, and else statements allow your program to execute different blocks of code based on conditions.
  • Comparison operators (==, !=, >, <, >=, <=) are used to create True or False conditions.
  • Indentation is crucial in Python. It's how you define which code belongs inside an if, elif, or else block.
  • The order of your if/elif checks matters, as Python stops at the first true condition it finds.
  • Logical operators (and, or) help you write cleaner, more readable conditions.

In our next lesson, we will explore another fundamental control flow concept: loops. Loops allow you to repeat a block of code multiple times, which is essential for tasks like animating characters, processing lists of items, or making enemies patrol an area. Combining decisions with loops will unlock a massive range of possibilities for your game.