SuperRobots

Back to Tutorials

Introduction to Conditionals: Teaching Your Robot to Decide

Imagine you're walking through a dungeon and you reach a fork in the path. To the left, you see a locked door. To the right, the path is clear. What do you do? You decide based on the situation. Conditionals let your robot do the exact same thing — make decisions based on what's happening around it.

The "If" Statement

The most basic conditional is the if statement. It checks whether something is true, and if it is, runs a block of code.

if super_robot.isPathClear():
    super_robot.moveForward()

In plain English, this reads: "If the path ahead is clear, move forward." If the path is not clear, the robot simply does nothing and skips to the next instruction.

Adding "Else": A Backup Plan

What if you want the robot to do something different when the condition is false? That's what else is for.

if super_robot.isPathClear():
    super_robot.moveForward()
else:
    super_robot.turnRight()

Now the robot has a backup plan: if the path is clear, move forward. Otherwise, turn right. This simple pattern is incredibly powerful and is used in virtually every program ever written.

Getting Specific with "Elif"

Sometimes there are more than two options. The elif keyword (short for "else if") lets you chain multiple conditions together.

if super_robot.isEnemyAhead():
    super_robot.attack()
elif super_robot.isPathClear():
    super_robot.moveForward()
else:
    super_robot.turnLeft()

The robot now checks three scenarios in order: Is there an enemy ahead? If yes, attack. If no, is the path clear? If yes, move. If neither, turn left. Python checks each condition from top to bottom and runs only the first one that is true.

Boolean Values: True and False

Conditionals rely on boolean values — values that are either True or False. Functions like isPathClear() and isEnemyAhead() return booleans. You can also create your own:

health = 50
is_low_health = health < 30
print(is_low_health)  # Output: False

health = 20
is_low_health = health < 30
print(is_low_health)  # Output: True

Combining Conditions

You can combine multiple conditions using and and or:

  • and: Both conditions must be true — if health > 0 and has_sword:
  • or: At least one condition must be true — if is_trapped or health < 10:

Practice in the Dungeon

The best way to learn conditionals is to use them. Open the Cyber Dungeon and try writing code that reacts to enemies, walls, and items dynamically. Once you master if, elif, and else, your robot will stop blindly following instructions and start thinking for itself. 🤖