Reputation: 37
so I have this small task here, where I have to get user input, based on said input assign different values to variables and then print out the sum of it. If I go by doing 'if' within 'if' it would work, but that would be so much text to begin with. I'm trying to find a way to read user input and match it with a certain value. Maybe that's got something to do with data structures but I'm not that far into it yet. Any suggestions? Here's the code:
input1 = input()
day = input()
quantity = float(input())
if input1 not in ["banana", "apple", "orange", "grapefruit", "kiwi", "pineapple", "grapes"]:
print("error")
if day in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]:
banana = 2.50
apple = 1.20
orange = 0.85
grapefruit = 1.45
kiwi = 2.70
pineapple = 5.50
grapes = 3.85
elif day in ["Saturday", "Sunday"]:
banana = 2.70
apple = 1.25
orange = 0.90
grapefruit = 1.60
kiwi = 3
pineapple = 5.60
grapes = 4.20
else:
print("error")
price = input1 * quantity
print(f"{price}:.2f")
Upvotes: 0
Views: 686
Reputation: 265
As suggested in the comments, I would use a dictionary to handle this situation, and also exceptions to handle the cases where the fruit names/day names do not match what is expected. For example:
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
weekends = ['Saturday', 'Sunday']
fruit_prices = {
'banana': {'weekday': 2.5, 'weekend': 2.5},
'apple': {'weekday': 1.2, 'weekend': 1.25},
# ...rest
}
def get_price(fruit, day, quantity):
if fruit not in fruit_prices:
raise ValueError(f'no such fruit: {fruit}')
if day not in weekdays and day not in weekends:
raise ValueError(f'no such day: {day}')
price = fruit_prices[fruit]['weekday' if day in weekdays else 'weekend']
return price * quantity
_fruit = input().strip()
_day = input().strip()
_quantity = float(input().strip())
try:
print(get_price(_fruit, _day, _quantity))
except ValueError as err:
print(f'error: {str(err)}')
Upvotes: 1