The if and if-else Statements
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Programs make decisions based on runtime conditions. In Python, code blocks are defined strictly by indentation rather than curly braces.
The if statement and indentation
If statement is a line of code that runs an indented block only when its condition is True. When the condition is False, Python skips the block and moves on to the next line.
An if statement evaluates a condition. If the condition is truthy, the indented code block executes.
cart_total = 750if cart_total >= 500: print("Eligible for free shipping")Example 1 · A block that is skipped
order_total = 420if order_total >= 500: print("Free shipping")print("Order placed")Order placed
What this code does
420 >= 500is False, so the indented line is skipped.print("Order placed")is not indented, so it belongs to no block and always runs.
PEP 8 specifies exactly 4 spaces per indentation level. Mixing tabs and spaces produces an IndentationError.
The if-else statement
If-else statement is an if with a second block after else. Exactly one of the two blocks runs: the if block when the condition is True, the else block when it is False.
Use else to provide an alternative execution path when the if condition evaluates to false.
stock_count = 0if stock_count > 0: print("In Stock")else: print("Out of Stock")Example 2 · Approving a withdrawal
balance = 1200withdrawal = 500
if withdrawal <= balance: balance -= withdrawal print(f"Withdrawal approved. Remaining balance: {balance}")else: print("Insufficient funds")Withdrawal approved. Remaining balance: 700
What this code does
- Checks if withdrawal amount is within available balance.
- Deducts amount and prints approved balance since 500 <= 1200.
Both the if and else lines end with a colon :. Exactly one of the two blocks will execute.
Idiomatic truthiness testing
Truthiness is how Python treats any value as True or False inside a condition. Values such as 0, an empty string and None count as False. Most other values count as True.
Instead of writing if len(name) > 0: or if is_admin == True:, write concise, idiomatic Python checks.
username = "Anita"if username: print(f"Welcome back, {username}")Example 3 · Empty coupon field
coupon = ""if coupon: print(f"Coupon {coupon} applied")else: print("No coupon applied")No coupon applied
What this code does
- An empty string is falsy, so
if coupon:is False. - Python runs the
elseblock. Withcoupon = "SAVE10"the first line would run instead.
Because non-empty strings are truthy, if username: evaluates to True cleanly.
Next step
Check your understanding
8 quick questions