Lesson 6: Conditions

Module 3: Control Flow & Loops · about 10 min · free

These commands are used for conditional branching (decision-making). They allow you to execute different blocks of code based on whether specific conditions are true or false.

How if, elif, and else work:

  • if (If): This is the starting point of any decision. The computer checks if a given condition is true. If it is, the code inside the if block runs. If it's false, the computer skips it.
  • elif (Else If): Short for "else if". If the previous if condition was false, the computer can check another specific condition using elif. You can have multiple elif blocks to test different scenarios.
  • else (Else): This acts as the final catch-all option. If all preceding if and elif conditions turn out to be false, the code inside the else block runs automatically. It doesn't need a condition of its own because it handles everything else.
age = 15

if age < 6:
  print("The entry is free")
elif age < 18:
  print("The ticket price is 5€")
elif age < 65:
  print("The ticket price is 10€")
else:
  print("The ticket price is 4€")

Output

The ticket price is 5€

As you can see, we used logical operations. When building logical expressions, we use:

  • == equals
  • != does not equal
  • >= greater than or equal to
  • <= less than or equal to

Maybe you're asking why there are two equal signs? This is used when you don’t assign a value, but rather check if it equals that value, for example:

password = "SecretCode123"
input = "SecretCode123"
if password == input:
  print("Access granted!")
else:
  print("Access denied.")

Output

Access granted!

Want XP, levels and progress tracking? Play this lesson in the CodeStart game.

Play Lesson 6