Conditional Operators
Learn how to control program flow using if, elif, and else.
Conditional Operators
Now that we know comparison operators, we can use them to make decisions in our programs. Conditional operators allow you to execute different code depending on whether a condition is True or False.
The if Statement
The if statement executes a block of code only when a condition is True:
Notice there are no parentheses around the condition and no curly braces — just a colon : after the condition and an indented block below it. The indentation is what defines which lines belong to the if block.
The elif Statement
elif (short for "else if") lets you check additional conditions when the previous one was False:
You can chain as many elif blocks as needed. They are checked in order — as soon as one is True, the rest are skipped.
The else Statement
else handles everything that didn't match any of the previous conditions. It has no condition of its own:
else must always come last. Exactly one branch in an if/elif/else chain will execute.
More if Patterns
Not every situation calls for a chain. Sometimes you need two separate, independent if statements that are both always checked:
Here both conditions are checked regardless of each other. A student with a score of 95 will see both messages printed. This is different from elif, where only one branch can execute.
You can also place an if inside another if — this is called a nested condition. It is useful when the inner check only makes sense if the outer one already passed:
The inner if/elif/else only runs if the age is within a valid range. Nesting keeps the logic clean — you don't have to repeat the range check in every branch.
Logical Operators: and, or, not
Python uses plain English words for logical operators.
Here is a complete truth table showing how they behave with two boolean values A and B:
A |
|---|