Codiqo

Learn Python · lesson 16 of 60 · about 9 minutes

Project: Spending Check

Ask how much Sam spent this week and say how it went: reject an impossible amount, then sort the rest with an if / elif chain.

What you'll learn

  • Order elif conditions correctly
  • Validate input ranges
  • Combine decisions with output

Where did the money go?

Sam saves 15 a week, but some weeks the money goes on snacks instead. The assistant should ask how much was spent this week and say how it went: nothing spent, within the 15, or over it. It also shouldn't accept a negative amount.

The rules

1. Below 0: Spending can't be negative
2. Exactly 0: Nothing spent: all 15 saved!
3. Up to 15: within budget, and how much was saved
4. More than 15: over budget, and by how much

Check the impossible value first, then go up from the smallest amount. Because only the first True branch runs, each elif only needs to check its upper limit.

The spending check

weekly = 15
spent = int(input("Spent this week? "))
if spent < 0:
    print("Spending can't be negative")
elif spent == 0:
    print(f"Nothing spent: all {weekly} saved!")
elif spent <= weekly:
    print(f"Within budget: {weekly - spent} saved")
else:
    print(f"Over budget by {spent - weekly}")

Output

Spent this week? Within budget: 3 saved

The grade calculator

score = int(input("Score: "))
if score < 0 or score > 100:
    print("That isn't a valid score.")
elif score >= 90:
    print("Grade A")
elif score >= 75:
    print("Grade B")
elif score >= 60:
    print("Grade C")
else:
    print("Keep practising")

Output

Score: Grade B

Tip

Test your programs with edge cases: the exact boundaries (90, 75, 60) and impossible values (−5, 120) are where bugs hide.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.