if / else
In this tutorial, we'll choose between two paths.
Use if / else when your program should choose between two paths.
age = 16
if age >= 18:
print("Adult ticket")
else:
print("Child ticket")
If the condition is true, the if block runs. Otherwise, the else block runs.
Why else Is Useful
Without else, you might write two separate conditions:
if age >= 18:
print("Adult ticket")
if age < 18:
print("Child ticket")
This works, but else is clearer because there are exactly two possibilities.
Example: Login
password = "python123"
if password == "python123":
print("Access granted")
else:
print("Access denied")
Only one branch can run.
else Has No Condition
Do not write a condition after else:
else password != "python123": # wrong
else means "anything that did not match the if".
Think of It as a Fork
An if / else is like a fork in the road. Python can go left or right, but not both.
has_homework = True
if has_homework:
print("Do homework first")
else:
print("Free time")
This makes it useful for clear yes/no decisions.
Practice
Create a variable called score. Print "Pass" if the score is at least 50. Otherwise print "Try again".