Python If...Else
The if statement lets your program choose what to do based on a condition.
The if Statement
Example
temperature = 38
if temperature > 35:
print("It is very hot today")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
age = 16
if age >= 18:
print("You can apply for a CNIC")
else:
print("You are too young for a CNIC")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
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)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
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!")You get a 10% discount Weekend!
Nested if
An if can be placed inside another if:
Example
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")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
marks = 45
result = "Pass" if marks >= 50 else "Fail"
print(result)Fail
pass
A block cannot be empty. If you want to write the code later, use pass as a placeholder:
Example
if True:
pass # will add code latermatch (Python 3.10 and newer)
When you compare one value against many options, match can be neater:
Example
choice = 2
match choice:
case 1:
print("Check balance")
case 2:
print("Withdraw cash")
case _:
print("Invalid option")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")
