+ 3

Python code - Coffee Machine

Hi everyone, my code passes all the tests except one, where it gives no output under the exception. I looked on Stack Overflow, GeeksforGeeks, a few other sites from Google searches and tried to tweak the code but still no luck. Can anyone help please? choice = int(input()) coffee = ["Café Latte", "Caffe Americano", "Espresso", "Cappuccino", "Macchiato"] try: #your code goes here #for i in choice: #for j in coffee.index(): #if i == j: #print(coffee[choice]) if choice in range(len(coffee)): print(coffee[choice]) except: #raise exception ("Invalid number") print("Invalid number") #and here #if choice not in range(len(coffee)): finally: #and finally here print("Have a good day")

12th Dec 2020, 7:58 AM
Charlie T
12 odpowiedzi
+ 7
"Where it gives no output under the exception" If I understood you correctly, you expect an output when the code encounters an exception from invalid index. If this was the issue, then remove if choice in range(len(coffee)): That line prevents referencing an item from list <coffee> where an invalid index was given as <choice>.
12th Dec 2020, 8:13 AM
Ipang
+ 7
You already have the list of the coffee, so the choice will serve as your index. Example if the costumer order '1' then get the coffee by doing "coffee[1]' https://code.sololearn.com/cs3B8M2ufEao/?ref=app
12th Dec 2020, 8:16 AM
noteve
noteve - avatar
+ 3
coffee = ["Café Latte", "Caffe Americano", "Espresso", "Cappuccino", "Macchiato"] choice = int(input()) try: choice < 5 print(coffee[choice]) except: print("Invalid number") finally: print("Have a good day")
15th Oct 2021, 12:22 PM
Kholdarov Ilyosjon
Kholdarov Ilyosjon - avatar
+ 1
Thank you Ipang, that worked!
12th Dec 2020, 8:21 AM
Charlie T
+ 1
Thank you Nicko12, that worked!
12th Dec 2020, 8:22 AM
Charlie T
+ 1
You can try this: coffee = ["Café Latte", "Caffe Americano", "Espresso", "Cappuccino", "Macchiato"] choice = int(input()) len1 = len(coffee) try: choice < len1 print(coffee[choice]) except: print("Invalid number") finally: print("Have a good day")
19th Mar 2021, 11:15 AM
Somnath Das
Somnath Das - avatar
0
Thank you Somnath!
19th Mar 2021, 11:36 AM
Charlie T
0
coffee = ["Café Latte", "Caffe Americano", "Espresso", "Cappuccino", "Macchiato"] choice = int(input()) try: print(coffee[choice]) except: if choice>=5: print("Invalid number") finally: print("Have a good day")
5th Jun 2021, 4:29 PM
fasak_kasak
0
Thank you Ilyosjon
15th Oct 2021, 12:27 PM
Charlie T
0
This woks for me: coffee = ["Café Latte", "Caffe Americano", "Espresso", "Cappuccino", "Macchiato"] choice = int(input()) try: choice < 5 print(coffee[choice]) except: print("Invalid number") finally: print("Have a good day")
17th Nov 2021, 10:43 AM
Stefan Bartl
Stefan Bartl - avatar
0
Thank you Stefan
21st Nov 2021, 8:25 PM
Charlie T
0
thanks!
24th Nov 2021, 4:46 AM
Giu
Giu - avatar