Conditionals (if · elif · else)
Definition: A statement that controls the program so that it runs different code depending on a given condition
Structure
text
if condition1:
(runs when condition1 is true)
elif condition2:
(runs when condition1 is false and condition2 is true)
else:
(runs when all conditions are false)Example
python
score = 85
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
elif score >= 70:
print("Grade C")
else:
print("Grade F")
# output: Grade BComparison Operators
| Operator | Meaning | Example |
|---|---|---|
== | Equal | 5 == 5 → True |
!= | Not equal | 5 != 3 → True |
> | Greater than | 5 > 3 → True |
< | Less than | 5 < 3 → False |
>= | Greater than or equal | 5 >= 5 → True |
<= | Less than or equal | 5 <= 3 → False |
Logical Operators
| Operator | Meaning | Example |
|---|---|---|
and | And (both true) | (5 > 3) and (3 > 1) → True |
or | Or (at least one true) | (5 > 10) or (3 > 1) → True |
not | Opposite | not True → False |
Example using conditionals
python
age = 20
has_license = True
if age >= 18 and has_license:
print("You can drive")
else:
print("You cannot drive")
# output: You can driveSummary
| Concept | Summary |
|---|---|
| if/elif/else | Branching on conditions → different behavior depending on the situation |
| Comparison operators | Compare two values with == != > < >= <= |
| Logical operators | Combine conditions with and or not |
Reference: personal Notion study notes (onboarding course)
