0

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")
3
  • Does this answer your question? How do I create variable variables? In short, use a dict instead of variables. As a bonus, you can do if input1 not in d: to check if it's invalid. Commented Feb 23, 2021 at 19:13
  • 1
    like {'banana' : [price week , price week-end] , ..........} Commented Feb 23, 2021 at 19:26
  • input1 = input() week = input() how = input() col = int dict ={'banana' : [1 , 2]} if week == 'a': col = 0 if week == 'b': col = 1 print(int(dict[input1][col])*int(how)) Commented Feb 23, 2021 at 19:48

1 Answer 1

1

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)}')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.