indusai.co

If, elif and else

Programs need to make decisions. The if statement runs a block of code only when a condition is true.

The if statement

python
temperature = 38
if temperature > 35:
    print("It is very hot today")

The condition can be any expression; Python tests its truthiness. The colon and the indented block are both required.

else

else runs when the condition is false.

python
marks = 28
if marks >= 33:
    print("Pass")
else:
    print("Fail")

elif

elif (short for else if) checks another condition when the previous ones were false. Python tests them from top to bottom and runs only the first block whose condition holds.

python
marks = 76
if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
elif marks >= 60:
    grade = "C"
else:
    grade = "D"
print(grade)

Order matters. If the checks were written from smallest to largest, marks >= 60 would match first and everything would be a C.

Combining conditions

python
age = 20
has_ticket = True

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

if age < 18 or not has_ticket:
    print("Entry denied")

Nested if

An if inside another if. Keep nesting shallow; more than two levels usually means the logic should be restructured or moved into a function.

python
n = 12
if n > 0:
    if n % 2 == 0:
        print("positive and even")
    else:
        print("positive and odd")
else:
    print("not positive")

Conditional expressions

A one line if that produces a value. Use it for simple choices only.

python
n = 7
parity = "even" if n % 2 == 0 else "odd"
print(parity)

Truthiness in conditions

Because empty values are false, you can test collections directly:

python
cart = []
if not cart:
    print("Your cart is empty")

name = ""
display = name or "Anonymous"
print(display)

Comparing with None

python
result = None
if result is None:
    print("No result yet")

Practice

  1. Write code that takes a number and prints whether it is negative, zero or positive.
  2. Given hour = 15, print "Good morning", "Good afternoon" or "Good evening" depending on the value.
  3. Rewrite the grade example so it also prints "Invalid" when marks are below 0 or above 100.