+ 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")
12 Respostas
+ 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>.
+ 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
+ 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")
+ 1
Thank you Ipang, that worked!
+ 1
Thank you Nicko12, that worked!
+ 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")
0
Thank you Somnath!
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")
0
Thank you Ilyosjon
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")
0
Thank you Stefan
0
thanks!