Conditions inside conditions
The block of an if can contain any statements, another if among them. A conditional statement inside another one is a nested conditional. Here the outer if checks that the price makes sense at all, and the inner one whether there's enough money:
balance = 50
price = int(input("Price: "))
if price > 0:
if price <= balance:
print("Purchase approved.")
else:
print("Not enough money.")
else:
print("That's not a valid price.")
80Price: 80
Not enough money.The inner statement is checked only when the outer condition is true. With a price of -5, Python goes straight to the outer else.
The indentation decides
In nested statements the indentation shows which else belongs to which if: an else belongs to the if above it at the same indentation. Move the inner else four spaces to the left, and the program means something else:
balance = 50
price = int(input("Price: "))
if price > 0:
if price <= balance:
print("Purchase approved.")
else:
print("Not enough money.")
80Price: 80Now the else belongs to the outer if. A price of 80 prints nothing at all, and a price of -5 would say Not enough money. Python has no way to know which one you meant, so get the indentation right.
Nested or combined?
The same decision can often be written with and instead of nesting:
balance = 50
price = 30
if price > 0 and price <= balance:
print("Purchase approved.")
elif price > 0:
print("Not enough money.")
else:
print("That's not a valid price.")
Purchase approved.Pick whichever version is easier to follow. Nesting fits well when a second question only makes sense after the first one, for example when the program asks for more input in only one branch. A combined condition keeps short checks flat and easy to scan.