← Learning Hub
Beginner

Conditions: if, elif, else

Use if to run code only when something is true. Note the colon : and the indented lines.

Programs need to make decisions: show "Free delivery" only if the total is big enough, allow sign-in only if the password is right, give a discount only to members. if is how a program chooses what to do.

Python checks the conditions from top to bottom and runs the first block whose condition is true. Then it skips the rest. elif means "else, if" - another condition to try. else catches everything that didn't match. You can have many elifs, or none.

Example
You can edit this code.

Comparing and combining

  • == equal, != not equal, < > <= >=
  • and: both must be true. or: at least one. not: flips True and False.

A condition always becomes either True or False. Combining them is like everyday rules: "you get the offer if you are a member and the cart is above Rs 500", or "delivery is free if it's Diwali or you have a coupon". Use brackets when mixing and and or to make your meaning clear.

Example
You can edit this code.

The last line is a conditional expression: a short one-line if/else that picks a value. Use it for simple choices like a label; for anything longer, a normal if block is easier to read.

Use == to compare and = to store a value. Mixing them up is a very common mistake.
Key points
  • if / elif / else choose which code runs; only the first true branch runs.
  • Conditions are True or False; combine them with and, or, not.
  • Don't forget the colon and the indentation.
  • == compares, = stores.

📝 Test yourself

1. Which keyword checks another condition after if?
2. What must come at the end of an if line?
3. Fill in the operator that checks if two values are equal:
if a b: