-2

I'm trying to take user input (as a string) and use this input as the variable needed to call a method of an object. The method is_resource_sufficient() of the object coffee_maker takes 'drink' as its variable however the input as a str doesn't work.

I have a Menu class which contains these three drinks and their resource requirements as attributes, so the line coffee_maker.is_resource_sufficient(latte) is valid. But when latte is replaced by drink_choice (and the input is latte) the line would then read coffee_maker.is_resource_sufficient('latte') which returns an error. So is there a way to change the input so that the answer returned is no longer a string?? I tried .strip('') but that still technically leaves a string.

I have gotten the whole code to work by just creating three seperate if statements (one for each drink as an input) so that I can write is_resource_sufficient(latte) etc for each however I'm really trying to work on reducing unnecessary length in my code.

The code here is:

drink_choice = input(f"What would you like? espresso/latte/cappuccino:").lower()

if drink_choice == 'espresso' or drink_choice == 'latte' or drink_choice == 'cappuccino':
    if coffee_maker.is_resource_sufficient(drink_choice) == True:
        print(f"You have chosen {drink_choice}.")

This is the working 'longer' code:

if drink_choice == 'espresso':
    if coffee_maker.is_resource_sufficient(espresso) == True:
        print()
        print(f"You have chosen an espresso. This costs ${espresso.cost}\n")

elif drink_choice == 'latte':
    if coffee_maker.is_resource_sufficient(latte) == True:
        print()
        print(f"You have chosen a latte. This costs ${latte.cost}\n")

elif drink_choice == 'cappuccino':
    if coffee_maker.is_resource_sufficient(cappuccino) == True:
        print()
        print(f"You have chosen a cappuccino. This costs ${cappuccino.cost}\n")
martineau
  • 112,593
  • 23
  • 157
  • 280
JoelGR
  • 21
  • 4
  • 2
    You don't need three separate `if` statements. Just change the original to `if drink_choice in ('espresso', 'latte', 'cappuccino'):`. – martineau May 28 '22 at 01:04
  • 1
    you just need f-string interpolation bro - like `f"You have chosen a {drink_choice}. This costs ${item.cost}\n"` – rv.kvetch May 28 '22 at 01:05
  • of course for good grammar you want to replace "a" with "an" for `espresso`. I think thats a good idea. I guess maybe just check if the first letter is a vowel? – rv.kvetch May 28 '22 at 01:07
  • Yeh I was worried about grammar so wrote them in dierctly. The problem is drink_choice when it's in the method is_resource_sufficient though. This returns an error stating the str doesn't contain any attributes :( – JoelGR May 28 '22 at 01:10
  • You will need to ask another question if you can't figure this new issue out. Be sure to include enough code. – martineau May 28 '22 at 01:12

0 Answers0