Lesson 1 of 5 · Control Flow · 2 min read · Updated

Making decisions with if

Run code only when a condition holds — and why Python cares about spaces.

Until now every line ran, every time. if lets the program choose.

python
marks = int(input("Marks out of 100: "))

if marks >= 90:
    print("Distinction")
elif marks >= 50:
    print("Pass")
else:
    print("Try again")
Output
Marks out of 100: 72
Pass

Indentation is the syntax

Most languages use braces to mark a block. Python uses the indentation itself. The spaces are not decoration — they are how Python knows which lines belong to the if.

Use four spaces, and be consistent. Mixing tabs and spaces is the most common beginner error, and the one hardest to see.

Warning

A missing colon at the end of the if line, or inconsistent indentation, gives an IndentationError or SyntaxError. Python is strict here on purpose: code that looks right reads right.

Combining conditions

python
if age >= 18 and has_id:
    print("Allowed")

if day == "Saturday" or day == "Sunday":
    print("Weekend")

if not found:
    print("Not found")

# Python lets you chain comparisons, which C cannot:
if 0 <= marks <= 100:
    print("Valid mark")

Note

Python spells them and, or, not rather than &&, ||, !. Same meaning, easier to read aloud.

How does Python know which lines belong inside an if?

Try this now

  1. Ask for an employee's basic salary and print the gross salary (basic + HRA + DA), where: basic up to 10000 gets HRA 20% and DA 80%; 10001 to 20000 gets HRA 25% and DA 90%; 20001 and above gets HRA 30% and DA 95%. Check: a basic of 15000 gives a gross of 32250.
  2. Ask for marks out of 100 and print the grade: 90+ A, 75+ B, 50+ C, otherwise Fail. Reject anything outside 0 to 100 first.

This lesson has 2 exercises for Blue Pearl students.

Enrolled at Blue Pearl Computer Education? Sign in with your roll number.

Create a free account to save your progress, or sign in.