0
Vending Machine Selection Malfunction
So, can someone help me with the solution? This is what I have so far, but I keep getting EOFErrors: products = ["Water", "Chocolate", "Chips", "Soda", "Sandwich"] choice_index = int(input(8)) try: print() # Write a try-except block to display the selected product except IndexError: print("Wrong Index") # or print "wrong index" if the input index is out of range
7 Respostas
+ 5
CodingTranslater638 ,
in the current code the upper bound of the index is `hard-coded` (5). giving an input of `5` will raise an IndexError, because the highest correct index for the current list is `4`
it is recommended to use the len(...) built-in function instead of the number of `5`.
also the comparison operator should be `<` instead of `<=`
> in general we should use a solution that implements a try... except... statement like:
...
try:
print(products[num])
...
+ 1
Where would this code display the selected product?
+ 1
1. Remove 8 from the input
2. Print the product at choice_ondex in the try-block
3. Check the spelling of the message in the except-block
+ 1
Lothar thanks!
0
In the try block, I'm not sure how to show the string paired with any available indexes
0
Thanks Lisa, ill try that
0
I have found the answer! It was this code for a different Vending Machine code, so I used that and changed it for it to work for my code! This was the winning code:
products = ["Water", "Chocolate", "Chips", "Soda", "Sandwich"]
num=int(input())
if num>=0 and num <=5:
print(products[num])
else:
print("wrong index")