Python conditionals practice VS Code real programs

Python conditionals practice β€” 3 real programs in VS Code

In the previous article we covered Python conditionals theory. Now it’s time to write real code. In this article we build three programs from scratch in VS Code using if, elif and else in real situations: a registration form validator, a customer loyalty discount system and a grade classifier with a menu. Each program starts simple and gains complexity, just like the exercises in FP1.

Create a folder called conditionals_practice and a separate file for each program.

Python conditionals practice β€” Program 1: Registration form validator

This program simulates the basic validation that any website does when you register. Create the file validator.py.

Simple version first:

# Registration validator β€” simple version
print("=== USER REGISTRATION ===\n")

username = input("Username: ")
age = int(input("Age: "))
password = input("Password: ")

if len(username) < 3:
    print("Error: username must be at least 3 characters")
elif age < 18:
    print("Error: you must be 18 or older")
elif len(password) < 6:
    print("Error: password must be at least 6 characters")
else:
    print("Registration successful")

This works but only detects the first error. The improved version detects all errors at once and gives complete feedback:

# Registration validator β€” improved version
print("=== USER REGISTRATION ===\n")

username = input("Username: ")
age = int(input("Age: "))
password = input("Password: ")
email = input("Email: ")

errors = 0

print("\n--- Validation results ---")

if len(username) < 3:
    print("βœ— Username too short (minimum 3 characters)")
    errors += 1
else:
    print("βœ“ Valid username")

if age < 18:
    print("βœ— Must be 18 or older")
    errors += 1
else:
    print("βœ“ Valid age")

if len(password) < 6:
    print("βœ— Password too short (minimum 6 characters)")
    errors += 1
elif not any(c.isdigit() for c in password):
    print("βœ— Password must contain at least one number")
    errors += 1
else:
    print("βœ“ Valid password")

if "@" not in email or "." not in email:
    print("βœ— Invalid email")
    errors += 1
else:
    print("βœ“ Valid email")

print(f"\n{'Registration complete' if errors == 0 else f'Registration failed β€” {errors} error(s) found'}")

Output:

=== USER REGISTRATION ===

Username: Jo
Age: 20
Password: abc
Email: sergio@sergiolearns.com

--- Validation results ---
βœ— Username too short (minimum 3 characters)
βœ“ Valid age
βœ— Password too short (minimum 6 characters)
βœ“ Valid email

Registration failed β€” 2 error(s) found

Notice the ternary operator at the end for the result message, one line instead of a full if/else. We also use not in to check if @ or . aren’t in the email, a very Pythonic way to do text checks.

Python conditionals practice β€” Program 2: Customer discount system

This program classifies customers by their annual spending and applies different discounts. Create the file customer_discounts.py.

# Customer discount system
print("=== LOYALTY SYSTEM ===\n")

name = input("Customer name: ")
annual_spend = float(input("Annual spend (€): "))
is_member = input("Member? (y/n): ").lower() == "y"

# Determine tier and base discount
if annual_spend >= 5000:
    tier = "Platinum"
    discount = 20
elif annual_spend >= 2000:
    tier = "Gold"
    discount = 15
elif annual_spend >= 500:
    tier = "Silver"
    discount = 10
else:
    tier = "Basic"
    discount = 5

# Extra discount for members
if is_member:
    extra_discount = 5
    total_discount = discount + extra_discount
else:
    extra_discount = 0
    total_discount = discount

# Calculate savings
savings = round(annual_spend * total_discount / 100, 2)
net_spend = round(annual_spend - savings, 2)

# Output
print(f"\n--- {name}'s profile ---")
print(f"Annual spend:     {annual_spend} €")
print(f"Tier:             {tier}")
print(f"Base discount:    {discount}%")

if is_member:
    print(f"Member bonus:     +{extra_discount}%")

print(f"Total discount:   {total_discount}%")
print(f"Savings:          {savings} €")
print(f"Net spend:        {net_spend} €")

# Personalised message by tier
if tier == "Platinum":
    print("\n⭐ Platinum β€” exclusive event access")
elif tier == "Gold":
    print("\nπŸ₯‡ Gold β€” free shipping on all orders")
elif tier == "Silver":
    print("\nπŸ₯ˆ Silver β€” early access to sales")
else:
    print("\nℹ️ Spend €500+ annually to reach Silver tier")

Output:

=== LOYALTY SYSTEM ===

Customer name: Sergio
Annual spend (€): 2500
Member? (y/n): y

--- Sergio's profile ---
Annual spend:     2500.0 €
Tier:             Gold
Base discount:    15%
Member bonus:     +5%
Total discount:   20%
Savings:          500.0 €
Net spend:        2000.0 €

πŸ₯‡ Gold β€” free shipping on all orders

Notice the very useful pattern here, using if/elif/else to assign values to variables (tier, discount) and then using those variables throughout the rest of the program. Much cleaner than repeating conditions everywhere.

Python conditionals practice β€” Program 3: Grade classifier with menu

The most complete of the three. Create the file grade_classifier.py. It combines a selection menu with conditionals to offer different analyses:

# Grade classifier with menu
print("=== GRADE CLASSIFIER ===")
print("1. Classify a grade")
print("2. Compare two grades")
print("3. Calculate minimum grade needed")

option = int(input("\nChoose option (1-3): "))

if option == 1:
    grade = float(input("\nEnter grade (0-10): "))

    if grade < 0 or grade > 10:
        print("Error: grade must be between 0 and 10")
    elif grade >= 9:
        classification = "Outstanding"
        emoji = "πŸ†"
    elif grade >= 7:
        classification = "Merit"
        emoji = "⭐"
    elif grade >= 5:
        classification = "Passed"
        emoji = "βœ“"
    elif grade >= 3:
        classification = "Failed"
        emoji = "βœ—"
    else:
        classification = "Very poor"
        emoji = "❌"

    if 0 <= grade <= 10:
        print(f"\n{emoji} Grade {grade} β€” {classification}")
        if grade < 5:
            print(f"Need {round(5 - grade, 1)} more points to pass")
        else:
            print(f"{round(grade - 5, 1)} points above pass mark")

elif option == 2:
    grade1 = float(input("\nGrade 1: "))
    grade2 = float(input("Grade 2: "))

    if grade1 > grade2:
        print(f"\nGrade 1 ({grade1}) is higher by {round(grade1 - grade2, 1)} points")
    elif grade2 > grade1:
        print(f"\nGrade 2 ({grade2}) is higher by {round(grade2 - grade1, 1)} points")
    else:
        print(f"\nBoth grades are equal ({grade1})")

    average = round((grade1 + grade2) / 2, 2)
    print(f"Average: {average} β€” {'Passed' if average >= 5 else 'Failed'}")

elif option == 3:
    current_count = int(input("\nHow many grades do you have so far?: "))
    total = 0

    for i in range(current_count):
        grade = float(input(f"Grade {i+1}: "))
        total += grade

    total_subjects = int(input("Total subjects in the course?: "))
    min_needed = round((5 * total_subjects - total) / (total_subjects - current_count), 2)

    if min_needed <= 0:
        print("\nβœ“ Pass already secured")
    elif min_needed <= 10:
        print(f"\nYou need at least {min_needed} in the remaining subjects")
    else:
        print("\nβœ— Mathematically impossible to reach a passing average")

else:
    print("Invalid option β€” choose between 1 and 3")

Output with option 1:

=== GRADE CLASSIFIER ===
1. Classify a grade
2. Compare two grades
3. Calculate minimum grade needed

Choose option (1-3): 1

Enter grade (0-10): 6.5

βœ“ Grade 6.5 β€” Passed
1.5 points above pass mark

Option 3 already uses a for loop, the next topic we’ll cover. Don’t worry if you don’t fully understand it yet, the important thing right now is the conditionals.

The pattern you’ll use most in FP1

Of everything we’ve seen, this is the pattern that appears most in class exercises:

# Pattern: classify with if/elif/else and store in variable
value = float(input("Enter a value: "))

if value >= high_threshold:
    category = "High"
elif value >= mid_threshold:
    category = "Medium"
else:
    category = "Low"

# Use the variable later
print(f"Category: {category}")

Learn this pattern well, you’ll see it for grades, temperatures, ages, prices and many other situations.

Visualise it with Python Tutor

Paste Program 2 into pythontutor.com (select Python 3) and step through it with an annual spend of 2500 and member = True. Watch how Python evaluates each if/elif condition in order, stops at the first matching one (tier = "Gold"), then processes the membership bonus separately. You’ll see exactly when each variable (tier, discount, total_discount) gets its value assigned.

Summary and next step

In this article you practised Python conditionals with three real programs. You used if/elif/else to classify, validate and compare data, the ternary operator for single-line results, not in to check text content, and the pattern of assigning values with conditionals.

In the next article in this series you’ll find proposed exercises with solutions, including the classic number guessing game.

Similar Posts

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *