KTU S1

Selection in Python — if, elif, else

By the end you should be able to: Write Python selection statements using if, elif and else, explain how indentation defines a block, and evaluate truthiness and chained comparisons correctly.

Module 2's IF … THEN … ELSE … ENDIF becomes this in Python:

if marks >= 50:
    print("Pass")
else:
    print("Fail")

Three differences from the pseudocode:

  • A colon ends the condition line.
  • Indentation defines the block — there is no ENDIF.
  • elif replaces ELSE IF.

Indentation is the syntax

In most languages indentation is a courtesy. In Python it is the block structure, and getting it wrong changes what the program does.

if marks >= 50:
    print("Pass")
    print("Well done")      # inside the if

if marks >= 50:
    print("Pass")
print("Well done")          # ALWAYS runs

Use 4 spaces. Never mix tabs and spaces — Python 3 raises TabError, and the two look identical on screen, which makes it a genuinely nasty bug to find.

The chain

if marks >= 90:
    grade = "S"
elif marks >= 85:
    grade = "A+"
elif marks >= 80:
    grade = "A"
else:
    grade = "F"

Same rule as Module 2: first true condition wins, so order from most restrictive to least. Only one branch ever runs.

Truthiness

if accepts any value, not just True/False. These are all falsy:

False   None   0   0.0   ""   []   ()   {}   set()

Everything else is truthy. So:

if marks:           # WRONG for marks == 0 — treats 0 as "no marks"
if marks > 0:       # says what you mean

But it's genuinely useful for containers:

if not names:
    print("The list is empty")

Chained comparisons

Python allows what maths allows, and it means what you'd expect:

if 0 <= marks <= 100:       # both must hold

This is not just shorter than marks >= 0 and marks <= 100 — it is also evaluated once, so it cannot disagree with itself.

The = versus == trap

if marks = 50:      # SyntaxError
if marks == 50:     # comparison

Python makes this a syntax error rather than a silent bug, which is a kindness — in C the first version compiles and assigns.

Conditional expression

For a simple two-way choice, on one line:

status = "Pass" if marks >= 50 else "Fail"

Readable for short cases. Don't nest them.