๐Ÿ“Š We use cookies & analytics to improve your experience. Learn more
Latest

Python for Absolute Beginners Module 2 ยท Lesson 4 of 15

0% Exit to course

Module 2 ยท Making the program decide Lesson 4 of 15

if, elif, else

Learning objective

A condition is a yes/no question the program asks itself. Indentation is the syntax in Python โ€” four spaces make the block, and nothing else does.

The concept

A condition is a yes-or-no question the program asks itself, and the branch it takes decides what happens next. if marks >= 75: prints a distinction, elif marks >= 40: prints a pass, else: handles everything left. Python runs the FIRST true branch and stops looking, which is why the order of the conditions is part of the logic, not decoration.

The syntax rule that trips everyone is indentation. In most languages a block is marked with braces; in Python it is four spaces. Your editor inserts them for you if you end a line with a colon โ€” take the help. Conditions combine with and, or and not, and you can compare text as well as numbers: if city.lower() == "pune": ignores how the person capitalised it.

Python
marks = 82

if marks >= 75:
    print("Distinction")
elif marks >= 40:
    print("Pass")
else:
    print("Needs work")

Common mistakes

The mistake is putting the broad condition first: with if marks >= 40 written above if marks >= 75, a distinction never reaches its own branch. Read your conditions top to bottom and ask what each one has already ruled out.

Worked example

if marks >= 40: print("Pass") elif marks >= 75: print("First class") else: print("Needs work") โ€” order matters, because the first true branch wins.

Your practice task

Write a program that labels a number as positive, negative or zero, then extend it to label a mark as fail, pass, first class or distinction.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

A condition is a yes-or-no question the program asks itself, and the branch it takes decides what happens next.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task โ€” do them and the final project brief writes itself.