// Data Structures
Dict Mini Project — Tip Calculator
What you're building
A tip calculator. The user enters the bill amount and rates the service. The program looks up the tip percentage from a dict and calculates how much to leave.
What you need to know first
- Dicts — creating and reading
- Square bracket lookup and
get() into check if a key existsinput()andfloat()if / elif / else
The brief
Build a program that:
- Stores tip percentages in a dict:
"poor"→ 10%,"good"→ 15%,"excellent"→ 20% - Asks the user for the bill amount
- Asks the user to rate the service: poor, good, or excellent
- Looks up the percentage in the dict
- Calculates and prints the tip amount and the total bill
- Handles an invalid rating gracefully
Think before you code
- What type should the bill amount be?
- How do you look up the rating in the dict safely?
- What do you do if the user types something that isn't a valid rating?
- How do you calculate the tip and the total from a percentage stored as a decimal?
Your starting point
tips = {
"poor": 0.10,
"good": 0.15,
"excellent": 0.20
}
bill = float(input("Bill amount: $"))
rating = input("Service (poor / good / excellent): ").lower()
# your code here
Expected output
Bill amount: $85
Service (poor / good / excellent): good
Tip (15%): $12.75
Total: $97.75
Bill amount: $85
Service (poor / good / excellent): amazing
Invalid rating. Choose: poor, good, or excellent.
Heads up!
- Use
.lower()on the input so"Good"and"GOOD"both work - The percentage is stored as a decimal —
0.15means 15% - Use
into check if the rating is valid before looking it up - Format the output with
:.2ffor two decimal places
The solution
tips = {
"poor": 0.10,
"good": 0.15,
"excellent": 0.20
}
bill = float(input("Bill amount: $"))
rating = input("Service (poor / good / excellent): ").lower()
if rating in tips:
percentage = tips[rating]
tip = bill * percentage
total = bill + tip
print(f"\nTip ({int(percentage * 100)}%): ${tip:.2f}")
print(f"Total: ${total:.2f}")
else:
print("Invalid rating. Choose: poor, good, or excellent.")
// resources
// 0 comments
// No comments yet. Be the first.
// leave a comment