6. Python If / Else
Python If / Else
A program that runs the same code every time regardless of conditions is not very useful. Conditional statements let your program make decisions — executing certain blocks of code only when specific conditions are met.
In Python, the keywords if, elif, and else are the building blocks of all decision-making logic. Every login check, every form validation, every game rule comes down to these three keywords.
The if Statement
The if statement evaluates a condition. If that condition is True, the indented block of code beneath it runs. If it is False, Python skips that block entirely.
The colon : after the condition is mandatory. The indented lines below form the body of the if block. Python uses indentation (4 spaces is the standard) to define which lines belong to the block.
The else Clause
The else clause defines what happens when the if condition is False. It is optional but covers the case where none of the conditions matched.
Exactly one branch of an if/else will always execute. Never both, never neither (as long as there is an else).
The elif Clause
elif is short for "else if." It lets you chain multiple conditions together. Python evaluates them top to bottom and executes the first one that is True, then skips all the rest.
Even though score >= 70 and score >= 60 are both True for score = 72, Python stops at the first True condition and never checks the rest.
Nested if
You can place an if statement inside another if statement. This is called nesting. It lets you check secondary conditions only when a primary condition has already passed.
Short-hand if (One-liner)
If the body of an if statement is a single line, you can write it on the same line as the condition. This is called the short-hand if or one-liner syntax.
Ternary Operator (Short-hand if-else)
Python has a concise one-line ternary expression that assigns one of two values based on a condition. The syntax is: value_if_true if condition else value_if_false.
The ternary operator is ideal for simple assignments where the logic is clear at a glance. For complex logic with multiple conditions, always use the full if/elif/else format for readability.
The pass Statement
Python does not allow empty code blocks — a block with no statements is a SyntaxError. The pass keyword is a placeholder that does absolutely nothing. It tells Python "this block is intentionally empty for now."
pass is used during development as a stub — you define the structure of your code first, put pass inside empty blocks, and fill in the logic later. It is also used in empty class and function definitions.
Knowledge Check
Ready to test your understanding of 6. Python If / Else?