Conditional Statements (if, elif, else)
The if statement is used to check a condition: if the condition is true, we run a block of statements (called the if-block ), else we process another block of statements (called the else-block ). The else clause is optional.
What Conditionals Do
Every program makes decisions. When you check your email, the program asks: Is there a new message? If yes, it shows a notification. If no, it stays silent. This decision-making is the job of conditional statements. A conditional statement checks whether something is true or false, then runs different code depending on the answer. In Python, we use if, elif, and else to build these decision points into our programs.
Imagine a security system at a door. If your ID is valid, the door unlocks. If your ID is invalid, the door stays locked and an alarm sounds. The system doesn't do both—it checks the condition (Is the ID valid?) and then follows one path or the other. Conditional statements work the same way: they evaluate a condition and choose which block of code to run.
The if Statement: Checking a Single Condition
The if statement is the foundation of all conditionals. It checks a condition and runs a block of statements if that condition is true. The block of code that runs is called the if-block. If the condition is false, the if-block is skipped entirely, and the program continues with whatever comes after the if statement.
The if-block is the set of statements that execute when an if statement's condition evaluates to true. These statements are grouped together through indentation.
You are an adult.
Program continues here.What do you think happens?
What will this code print if age is 16 instead of 18?
Reveal answer
Answer: Program continues here.
When age is 16, the condition age >= 18 is false. The indented print statement inside the if-block is skipped. Only the line outside the if block (not indented) runs, so we see only 'Program continues here.'
Adding an else Clause for the False Case
Often you want to run one block of code if a condition is true and a different block if it is false. This is where the else clause comes in. The else clause is optional—you can write an if statement without it. But when you include else, it provides a fallback: if the condition is false, the else-block runs instead. Only one of the two blocks will ever execute.
The else-block is the set of statements that execute when an if statement's condition evaluates to false. Like the if-block, the else-block is grouped through indentation.
You are not yet an adult.
Program continues here.In an if-else structure, exactly one of the two blocks will run. The program never runs both the if-block and the else-block in the same execution.
Handling Multiple Conditions with elif
Sometimes you need to check more than two possibilities. For example, you might want to assign a letter grade based on a test score: A for 90 and above, B for 80 to 89, C for 70 to 79, and so on. You could nest multiple if-else statements, but that creates deep indentation and is hard to read. Instead, use elif (short for else-if). The elif clause lets you chain multiple conditions together in a single, readable structure. You can have as many elif clauses as you need, and they are checked in order from top to bottom. The first condition that is true wins—its block runs, and all the others are skipped. If none of the conditions are true, an optional else clause runs as a final fallback.
The elif clause combines an else and an if into one statement. It allows you to check a new condition only if the previous condition was false, reducing indentation and improving readability.
Grade: B
Program continues here.Tracing Execution Through a Conditional Chain
To understand how elif chains work, it helps to trace through the execution step by step. Let's walk through a complete example that shows how the program evaluates each condition and decides which block to run.
Guessing Game Logic
A number-guessing game checks the player's guess against the secret number (42). If the guess is too high, it says 'Too high!' If the guess is too low, it says 'Too low!' If the guess is correct, it says 'You got it!' Trace the execution when the player guesses 30.
Set up the values: secret = 42, guess = 30
Check the first condition: Is guess == secret? Is 30 == 42? No, this is false. Skip the first if-block.
Check the first elif condition: Is guess > secret? Is 30 > 42? No, this is false. Skip this elif-block.
Check the second elif condition: Is guess < secret? Is 30 < 42? Yes, this is true. Run this elif-block.
Execute the matching block: Print 'Too low!' and then skip all remaining elif and else clauses.
Continue: The program moves to the next statement after the entire if-elif-else chain.
The output is 'Too low!' because the condition guess < secret was the first true condition encountered.
Syntax Rules: Colons and Indentation
Python uses indentation (spaces or tabs at the start of a line) to group statements into blocks. This is different from many other languages, which use curly braces or keywords. In conditional statements, every line that belongs to an if-block, elif-block, or else-block must be indented by the same amount. The if, elif, and else keywords themselves are not indented—they sit at the same level as each other. Each of these keywords must be followed by a colon (:) at the end of the line.
The elif and else statements must also have a colon at the end of the logical line followed by their corresponding block of statements with proper indentation.
It is warm.
Enjoy the day.
Done.When else and elif Are Optional
A minimal valid if statement requires only the if keyword, a condition, a colon, and an indented block. The elif and else parts are optional. You can write an if statement by itself, and if the condition is false, the program simply skips the block and continues. This is useful when you only need to do something if a condition is true, and there is no alternative action needed.
Welcome, Alice!
Login complete.In this example, if username were 'bob' instead, the if-block would be skipped, and only 'Login complete.' would print. No error occurs—the program runs fine without an else clause.
Common Mistakes
Forgetting the colon after if, elif, or else
Python requires a colon to mark the end of the condition line. Without it, you get a syntax error and the program will not run.
Fix:
if age >= 18: print('Adult')Incorrect indentation or mixing indentation styles
The print statement is not indented, so Python thinks it is outside the if-block. The statement will run regardless of the condition, which is not the intended behavior.
Fix:
if score > 80: print('Pass')Using = (assignment) instead of == (comparison) in a condition
The = operator assigns a value; it does not compare. This causes a syntax error. Use == to check if two values are equal.
Fix:
if age == 18: print('Adult')Checking multiple conditions with and/or incorrectly
The second part '< 90' is incomplete—it lacks a variable to compare. Python does not understand what you are comparing.
Fix:
if score > 80 and score < 90: print('B grade')Assuming elif runs even when the previous if was true
If the first if condition is true, the elif is not checked. Only one block runs in an if-elif-else chain. If x is 10, only 'Greater than 5' prints.
Fix:
Understand that elif only runs if all previous conditions were false. This is the intended behavior—no correction needed, just correct your mental model.
Practical Notes and Best Practices
Practice
Write a conditional statement that checks a person's age and prints the appropriate message: 'Child' if age is less than 13, 'Teen' if age is 13 to 19, 'Adult' if age is 20 to 64, and 'Senior' if age is 65 or older. Test your code with at least three different ages.
Hints
- Use if for the first condition and elif for the others.
- Think about the order: should you check the smallest ages first or the largest?
- Remember to use >= and < to define the ranges correctly.
Write a conditional statement that checks if a number is positive, negative, or zero. Print the appropriate message. Then, modify your code to also check if the number is even or odd (if it is not zero) and include that information in the message.
Hints
- Start with a simple if-elif-else for positive, negative, and zero.
- To check if a number is even, use the modulo operator: number % 2 == 0.
- You may need to nest conditions or use multiple if statements.
Summary
Conditional statements are the decision-makers of your programs. The if statement checks a condition and runs a block of code if it is true. The optional else clause provides a fallback block if the condition is false. The elif clause lets you chain multiple conditions together, checking them in order until one is true. Exactly one block in an if-elif-else chain will run (or none, if there is no else and all conditions are false). Always remember the colon after if, elif, and else, and always indent the statements that belong to each block. With these tools, you can write programs that respond differently to different inputs and make intelligent decisions.
Key Takeaways
- The if statement checks a condition and runs a block of code if the condition is true; the else-block is optional and runs if the condition is false.
- The elif clause allows you to check multiple conditions in sequence; the first true condition wins, and all others are skipped.
- Exactly one block in an if-elif-else chain executes, or none if there is no else and all conditions are false.
- Python uses indentation to group statements into blocks, and every if, elif, and else line must end with a colon.
- Order matters in elif chains—arrange conditions from most specific to most general to avoid unintended matches.