Python Docs

Nested - If - Else

You can have if statements inside if statements. This is called nested if statements.

Example

x = 41
if x > 10:
  print("Above ten,")
  if x > 20:
    print("and also above 20!")
  else:
    print("but not above 20.")

Output:

Above ten, and also above 20!

How Nested If Works

Each level of nesting creates a deeper level of decision-making. The code evaluates from the outermost condition inward.

Example

age = 25
has_license = True
if age >= 18:
  if has_license:
    print("You can drive")
  else:
    print("You need a license")
else:
  print("You are too young to drive")

Output:

You can drive