Conditional Operators
Using if, else, and else if statements
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.
Logical Operators: and, or, not
Python uses plain English words for logical operators — unlike C++ which uses &&, ||, !.
and
Both conditions must be True:
or
At least one condition must be True:
not
Inverts the result of a condition:
Combining Conditions
Logical operators have their own precedence: not is evaluated first, then and, then or. Use parentheses to make complex conditions readable:
Ternary Expression
Python has a compact one-line form of if/else for simple cases:
This is useful when you want to assign one of two values based on a condition. Don't overuse it — if the logic is complex, a regular if/else is clearer.
Complete Example
This program reads an integer and classifies it. Try tracing through it manually with a few values to make sure you understand which branch executes for each case.