Python If-Then and Case Examples

1. If-Then: Assign y and z

x = 150  # Initializing a variable 'x' with the integer value 150

if x > 100:
    y = 20
    z = 40

print("y:", y)
print("z:", z)

Explanation: If x > 100, assign y = 20 and z = 40.

2. If-Then: Assign b and c

a = 5

if a < 10:
    b = 0
    c = 1

print("b:", b)
print("c:", c)

Explanation: If a < 10, assign b = 0 and c = 1.

3. If-Then-Else: Assign b

a = 7

if a < 10:
    b = 0
else:
    b = 99

print("b:", b)

Explanation: If a < 10, assign b = 0. Otherwise, b = 99.

4. Nested If-Else: Student Grade

studentScore = 85

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

print("Grade:", grade)

5. Nested Decision: Compare amount1 and amount2

amount1 = 25
amount2 = 75

if amount1 > 10:
    if amount2 < 100:
        if amount1 > amount2:
            print("Greater value:", amount1)
        else:
            print("Greater value:", amount2)

6. Case Structure Variants

Using if-elif-else

selection = 2

if selection == 1:
    print("You selected A.")
elif selection == 2:
    print("You selected 2.")
elif selection == 3:
    print("You selected 3.")
elif selection == 4:
    print("You selected 4.")
else:
    print("Invalid selection.")

Using Dictionary

selection = 2

messages = {
    1: "You selected A.",
    2: "You selected 2.",
    3: "You selected 3.",
    4: "You selected 4."
}

print(messages.get(selection, "Invalid selection."))

Using match-case (Python 3.10+)

selection = 2

match selection:
    case 1:
        print("You selected A.")
    case 2:
        print("You selected 2.")
    case 3:
        print("You selected 3.")
    case 4:
        print("You selected 4.")
    case _:
        print("Invalid selection.")

7. If-Then-Else: Check Points Range

points = 55

if points < 9 or points > 51:
    print("Invalid points.")
else:
    print("Valid points.")

8. Case Structure for Month

month = 4

match month:
    case 1:
        print("January")
    case 2:
        print("February")
    case 3:
        print("March")
    case 4:
        print("April")
    case 5:
        print("May")
    case 6:
        print("June")
    case 7:
        print("July")
    case 8:
        print("August")
    case 9:
        print("September")
    case 10:
        print("October")
    case 11:
        print("November")
    case 12:
        print("December")
    case _:
        print("Invalid month")

Using String Match

month = "Feb"

match month:
    case "Jan":
        print("January")
    case "Feb":
        print("February")
    case "Mar":
        print("March")
    case _:
        print("Unknown month")

9. If-Then: Set hours based on flag

Using Integer Flag

minimum = 1

if minimum:
    hours = 10

print("Hours:", hours)

Using Boolean Flag

minimum = True

if minimum:
    hours = 10

print("Hours:", hours)

Additional Resources