Tutorials / Python from Scratch / Making decisions with if, elif and else

Making decisions with if, elif and else

12 min read python
Course contents (15 lessons)
  1. Getting started
  2. Installing Python 3.13 and running your first script
  3. Variables and basic data types
  4. Text, numbers and user input
  5. Working with strings
  6. Numbers and arithmetic
  7. Input and output: talking to the user
  8. Making decisions and repeating work
  9. Making decisions with if, elif and else
  10. Loops: for, while, break and continue
  11. Collections of data
  12. Lists and tuples
  13. Dictionaries and sets
  14. Functions and modules
  15. Writing your own functions
  16. Modules, pip and virtual environments
  17. Files and errors
  18. Reading and writing files
  19. Errors and exceptions
  20. Final project: expense tracker
  21. Project: build the expense tracker, part 1
  22. Project: summaries, search and improvements

Code that chooses

So far every line in your scripts ran, in order. Real programs need to choose. If the customer is a member, give a discount. If the stock is zero, show "out of stock". The if statement does this.

Comparisons produce True or False

A comparison asks a question and the answer is a bool.

OperatorMeaning
==equal to
!=not equal to
<, >less than, greater than
<=, >=less than or equal, greater than or equal

Note the double equals. One = stores a value. Two == compare. Writing if x = 5: is a syntax error, which is actually helpful because it catches the mix-up.

The if statement

weight_kg = float(input("Parcel weight in kg: "))
is_member = input("Are you a member? (y/n): ").strip().lower() == "y"

if weight_kg <= 0:
    print("Weight must be more than zero.")
elif weight_kg <= 1:
    cost = 200
elif weight_kg <= 5:
    cost = 450
else:
    cost = 450 + (weight_kg - 5) * 80

if weight_kg > 0:
    if is_member:
        cost = cost * 0.9
    print(f"Shipping cost: Rs {cost:.2f}")

If you enter 7 and answer y, the output is Shipping cost: Rs 549.00. The weight is above 5, so the cost is 450 + 2 * 80 = 610, and members get 10 percent off.

How it works

Python checks the conditions from the top. The first one that is true runs, and the rest are skipped. elif means "otherwise, if". else catches everything left over and has no condition. You can have as many elif parts as you want, or none. The else part is optional.

Look at the second if. It is nested inside the first. The inner if is_member: only runs when the outer one is true. Nesting works, but too much of it is hard to read. If you go three levels deep, try to simplify.

Indentation is the syntax

Most languages use curly braces to group lines. Python uses indentation. The lines that belong to an if are indented by four spaces, and the line before them ends with a colon. All lines in the same block must use the same indentation. Mixing tabs and spaces causes an IndentationError. Set your editor to insert four spaces when you press Tab and you will rarely see it.

and, or, not

Combine conditions with and, or and not.

age = 20
has_id = True

if age >= 18 and has_id:
    print("Entry allowed")

day = "Sat"
if day == "Sat" or day == "Sun":
    print("Weekend")

if not has_id:
    print("Please show your ID")

and needs both sides true. or needs at least one. A shorter way to write the weekend check is if day in ("Sat", "Sun"):.

Truthy and falsy values

Python treats some values as false in an if: 0, 0.0, the empty string "", empty collections and None. Everything else is true. So you can write:

name = input("Name: ").strip()
if not name:
    print("You did not type anything")

Chained comparisons

Python lets you write ranges the way you do in maths: if 18 <= age < 65:. This is true when age is at least 18 and below 65.

Common mistakes

  • Using = instead of ==. Described above.
  • Forgetting the colon. Every if, elif and else line ends with :.
  • Comparing text with numbers. "5" == 5 is False. If the input is text, convert it first.
  • Ordering conditions badly. In an elif chain, put the narrowest condition first. If you test weight <= 5 before weight <= 1, the second branch never runs.
  • Case differences. "Y" == "y" is false. Use .lower() on user input before comparing.

The conditional expression

For a simple choice between two values, one line is enough: label = "adult" if age >= 18 else "minor". Use it for short cases only. A long one-liner is worse than a plain if.

Try it yourself

Write a grade calculator. Ask for a mark from 0 to 100. Print "Invalid" if it is outside that range. Otherwise print A for 80 and above, B for 70 to 79, C for 60 to 69, D for 50 to 59 and F below 50. Test the edges: 79, 80, 50 and 49.

python
weight_kg = float(input("Parcel weight in kg: "))
is_member = input("Are you a member? (y/n): ").strip().lower() == "y"

if weight_kg <= 0:
    print("Weight must be more than zero.")
elif weight_kg <= 1:
    cost = 200
elif weight_kg <= 5:
    cost = 450
else:
    cost = 450 + (weight_kg - 5) * 80

if weight_kg > 0:
    if is_member:
        cost = cost * 0.9
    print(f"Shipping cost: Rs {cost:.2f}")

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account