Python Tutorial menu

Python If...Else

The if statement lets your program choose what to do based on a condition.

The if Statement

Example

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

If the condition is True, the indented block runs. If it is False, Python skips it.

else

else runs when the condition is False:

Example

python
age = 16
if age >= 18:
    print("You can apply for a CNIC")
else:
    print("You are too young for a CNIC")
Output
You are too young for a CNIC

elif

elif means "else if". Use it to check more than two possibilities. Python checks the conditions from top to bottom and runs only the first one that is true.

Example

python
marks = 82
if marks >= 90:
    grade = "A+"
elif marks >= 80:
    grade = "A"
elif marks >= 70:
    grade = "B"
elif marks >= 60:
    grade = "C"
else:
    grade = "Fail"
print("Grade:", grade)
Output
Grade: A

Even though 82 is also above 70 and 60, only the A block runs because it is the first match.

Combining Conditions

Example

python
bill = 4500
is_member = True
if bill > 3000 and is_member:
    print("You get a 10% discount")

day = "Sunday"
if day == "Saturday" or day == "Sunday":
    print("Weekend!")
Output
You get a 10% discount
Weekend!

Nested if

An if can be placed inside another if:

Example

python
balance = 2000
amount = 1500
pin_correct = True

if pin_correct:
    if amount <= balance:
        print("Please take your cash")
    else:
        print("Not enough balance")
else:
    print("Wrong PIN")
Output
Please take your cash

Too much nesting makes code hard to read. Often you can use and or elif instead.

Short if (Conditional Expression)

For a simple choice between two values, write it in one line:

Example

python
marks = 45
result = "Pass" if marks >= 50 else "Fail"
print(result)
Output
Fail

pass

A block cannot be empty. If you want to write the code later, use pass as a placeholder:

Example

python
if True:
    pass   # will add code later

match (Python 3.10 and newer)

When you compare one value against many options, match can be neater:

Example

python
choice = 2
match choice:
    case 1:
        print("Check balance")
    case 2:
        print("Withdraw cash")
    case _:
        print("Invalid option")
Output
Withdraw cash

case _ catches everything else, like else.

Exercise

Exercise

x = 7. What does this print? if x > 10: print("A") elif x > 5: print("B") else: print("C")

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp