Control Flow#

Control flow determines the direction of program execution. Python uses if/elif/else for conditional logic, combined with comparison operators, logical operators, and ternary expressions to handle branching scenarios with concise syntax.


if / elif / else#

Python uses if, elif, and else for conditional logic. Note that indentation is required:

1
2
3
4
5
6
7
8
age = 20

if age < 18:
    print("Minor")
elif age < 65:
    print("Adult")
else:
    print("Senior")

Multiple Conditions#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Grade: {grade}")  # Grade: B

Comparison Operators#

OperatorDescriptionExample
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater than or equal to5 >= 5True
<=Less than or equal to3 <= 5True

Logical Operators#

and#

Both conditions must be True for the result to be True:

1
2
3
4
5
age = 25
has_license = True

if age >= 18 and has_license:
    print("Allowed to drive")

or#

At least one condition must be True for the result to be True:

1
2
3
4
5
is_weekend = True
is_holiday = False

if is_weekend or is_holiday:
    print("Day off today")

not#

Reverses the boolean value:

1
2
3
4
is_raining = False

if not is_raining:
    print("Good time to go outside")

Combined Conditions#

1
2
3
4
5
6
temperature = 28
is_sunny = True
has_umbrella = False

if temperature > 25 and is_sunny and not has_umbrella:
    print("Hot and sunny, but no umbrella — watch out for sunburn")

Membership Operators: in and not in#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
fruits = ["apple", "banana", "cherry"]

if "banana" in fruits:
    print("Banana is in the list")

if "mango" not in fruits:
    print("Mango is not in the list")

# Also works with strings
email = "user@example.com"
if "@" in email:
    print("Valid email format")

Identity Operators: is and is not#

is checks whether two objects are the same object (same memory address), while == checks whether their values are equal :

1
2
3
4
5
6
7
# Conventionally use is to check for None
result = None
if result is None:
    print("No result yet")

# Avoid using == to compare with None
# if result == None:  # Works but not recommended

Ternary Expression (Conditional Expression)#

Python’s ternary expression syntax is value_a if condition else value_b:

1
2
3
4
5
6
7
8
9
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)  # Adult

# Equivalent to:
if age >= 18:
    status = "Adult"
else:
    status = "Minor"

Practical use:

1
2
3
4
5
6
7
score = 75
result = "Pass" if score >= 60 else "Fail"
print(result)  # Pass

# Can also be used inside print
x = -5
print(f"Absolute value of x is {x if x >= 0 else -x}")  # Absolute value of x is 5

match Statement (Python 3.10+)#

Python 3.10 introduced the match statement, similar to switch in other languages:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
command = "quit"

match command:
    case "start":
        print("Program started")
    case "stop":
        print("Program stopped")
    case "quit" | "exit":
        print("Exiting program")
    case _:
        print(f"Unknown command: {command}")

Practical Examples#

BMI Calculator and Classification#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
weight = 70  # kilograms
height = 1.75  # meters

bmi = weight / (height ** 2)
print(f"BMI: {bmi:.1f}")

if bmi < 18.5:
    category = "Underweight"
elif bmi < 24:
    category = "Normal"
elif bmi < 27:
    category = "Overweight"
else:
    category = "Obese"

print(f"Weight status: {category}")

Simple Calculator#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
a = 10
b = 3
operator = "+"

if operator == "+":
    result = a + b
elif operator == "-":
    result = a - b
elif operator == "*":
    result = a * b
elif operator == "/" and b != 0:
    result = a / b
elif operator == "/" and b == 0:
    result = "Error: division by zero"
else:
    result = "Unknown operator"

print(f"{a} {operator} {b} = {result}")

Leap Year Check#

1
2
3
4
5
6
7
8
year = 2024

is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

if is_leap:
    print(f"{year} is a leap year")
else:
    print(f"{year} is not a leap year")