Nested if Statements
This is a free course. Log in to run the code exercises and track your progress.
Nested if Statements
An if statement can sit inside another one. The inner decision is only reached when the outer condition is True. Each level is indented one step further.
a, b, c = 5, 5, 8
if a + b > c and b + c > a and a + c > b:
if a == b == c:
print("Equilateral")
elif a == b or b == c or a == c:
print("Isosceles")
else:
print("Scalene")
else:
print("Not a triangle")
The outer test checks that the three sides can form a triangle at all (each pair of sides must be longer than the third). Only then does the inner test decide its type. Python allows the chained comparison a == b == c, which means a == b and b == c.
Deep nesting is hard to read. When the branches do not depend on each other, a flat if/elif chain with and/or is usually clearer.
Read an age and whether the person has a voter ID (yes or no) from one line. Print Can vote if the age is 18 or more and the answer is yes, Get a voter ID if the age is 18 or more and the answer is no, and Too young otherwise. Use a nested if.
age, has_id = input().split()
age = int(age)
if age >= 18:
print("Can vote") # check has_id here with an inner if
else:
print("Too young")Log in to edit and run this code.