Skip to content

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 B

Comparison Operators ​

OperatorMeaningExample
==Equal5 == 5 → True
!=Not equal5 != 3 → True
>Greater than5 > 3 → True
<Less than5 < 3 → False
>=Greater than or equal5 >= 5 → True
<=Less than or equal5 <= 3 → False

Logical Operators ​

OperatorMeaningExample
andAnd (both true)(5 > 3) and (3 > 1) → True
orOr (at least one true)(5 > 10) or (3 > 1) → True
notOppositenot 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 drive

Summary ​

ConceptSummary
if/elif/elseBranching on conditions → different behavior depending on the situation
Comparison operatorsCompare two values with == != > < >= <=
Logical operatorsCombine conditions with and or not

Reference: personal Notion study notes (onboarding course)