An if statement runs a block of code only when a condition is true.
age = int(input("Age: "))
if age >= 18:
print("You may enter.")
print("Enjoy the show.")
print("Goodbye")Three details matter here:
- The condition ends with a colon.
- The lines that belong to the
ifare indented — four spaces, by convention. print("Goodbye")is not indented, so it runs either way.
Indentation is how Python marks a block. Other languages use braces; Python uses the layout you would have used anyway.
else and elif
else catches everything the if did not. elif (“else if”) adds another
question, and you can chain as many as you like.
score = int(input("Score out of 100: "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Score {score} earns a {grade}")Order matters enormously. Python checks the branches top to bottom and stops at
the first true one — so a score of 95 never reaches the >= 80 test. Write the
chain the wrong way round (>= 60 first) and every passing score becomes a D.
elif is not the same as a second if
A chain of elifs picks exactly one branch. A run of separate ifs tests
every condition independently, and several can fire. Both are useful — but they
mean different things.
n = 15
print("With elif:")
if n % 3 == 0:
print(" divisible by 3")
elif n % 5 == 0:
print(" divisible by 5")
print("With separate ifs:")
if n % 3 == 0:
print(" divisible by 3")
if n % 5 == 0:
print(" divisible by 5")Nesting, and how to avoid it
An if can contain another if. It can, but deeply nested conditions get hard
to follow fast.
username = input("Username: ")
password = input("Password: ")
# Nested: the happy path is buried at the deepest indent.
if username:
if password:
if len(password) >= 6:
print("Welcome back")
else:
print("Password too short")
else:
print("Password required")
else:
print("Username required")The same logic reads far better as a series of early exits, each handling one problem and getting out of the way:
username = input("Username: ")
password = input("Password: ")
if not username:
print("Username required")
elif not password:
print("Password required")
elif len(password) < 6:
print("Password too short")
else:
print("Welcome back")Same behaviour, one level of indentation, and every rule sits on its own line.
The conditional expression
When a whole if/else exists only to choose between two values, Python has a
one-line form:
count = 1
label = "item" if count == 1 else "items"
print(f"{count} {label}")
temperature = 31
print("hot" if temperature > 30 else "not hot")Use it for short, obvious choices. If you find yourself nesting one inside
another, go back to a normal if.
Fizz, Buzz, or the number
Print Fizz if the number divides by 3, Buzz if it divides by 5, FizzBuzz
if it divides by both, and otherwise the number itself. Try it with 9, 10, 15
and 7.
n = int(input("Number: "))
# Your code hereShow one solution
n = int(input("Number: "))
if n % 3 == 0 and n % 5 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)The combined case has to come first. Test it against 15 and you will see why —
put it last and 15 prints Fizz, because that branch matched before the
FizzBuzz test was ever reached.
What you learned
if condition:runs an indented block when the condition is true.elifadds alternatives;elsecatches the rest; exactly one branch runs.- Order your conditions from most specific to least.
- Guard clauses beat deep nesting.
a if condition else bchooses between two values inline.