0

Python core 43.2 the command "except:" does not work?

My code is below: coffee = ["Café Latte", "Caffe Americano", "Espresso", "Cappuccino", "Macchiato"] choice = int(input()) try: a = len(coffee) b = a-1 if 0<=choice<=b: print(coffee[choice]) # your code goes here except: print('Invalid number') # and here finally: print('Have a good day') When entering a number between 0 and 4, everything is fine. But if you enter a different number, it just prints what should be printed after the "finally:" I went through the task using code that is written below, but I would like to know what my mistake. Thanks. coffee = ["Café Latte", "Caffe Americano", "Espresso", "Cappuccino", "Macchiato"] choice = int(input()) a = len(coffee) b = a-1 if 0<=choice<=b: print(coffee[choice]) else: print('Invalid number') print('Have a good day')

27th Aug 2021, 12:02 PM
Tsimur Kuts
Tsimur Kuts - avatar
4 Antworten
+ 1
Tsimur Kuts The except function was never called because nothing tripped the try section. You have an if clause which will produce a result if the choice is within the coffee range. else -> NOTHING
27th Aug 2021, 12:20 PM
Rik Wittkopp
Rik Wittkopp - avatar
0
Let's say I added "else:" to show an empty line on the screen. coffee = ["Café Latte", "Caffe Americano", "Espresso", "Cappuccino", "Macchiato"] choice = int(input()) try: a = len(coffee) b = a-1 if 0<=choice<=b: print(coffee[choice]) else: print() except: print('Invalid number') finally: print('Have a good day') Nothing happens) Even in the code below, nothing happens if I understand correctly how it works a = int(input()) try: a == 2 except: print('Invalid number') Most likely somewhere my mistake, but I do not know where, or I do not understand how it should work
27th Aug 2021, 12:37 PM
Tsimur Kuts
Tsimur Kuts - avatar
0
Tsimur Kuts By creating the if statement, the code now looks for an option outside the range of the coffee list, which is usually handled by the else statement. I have a little code below which will explain, I hope coffee = ["Café Latte", "Caffe Americano", "Espresso", "Cappuccino", "Macchiato"] choice = int(input()) try: print(coffee[choice]) except: print('Invalid number') finally: print('Have a good day')
27th Aug 2021, 10:11 PM
Rik Wittkopp
Rik Wittkopp - avatar
0
Totalt new at this but I think you can make it work in a easier way: coffee = ["Café Latte", "Caffe Americano", "Espresso", "Cappuccino", "Macchiato"] choice = int(input()) try: print(coffee[choice]) except: print("Invalid number") finally: print("Have a good day")
31st Dec 2021, 12:42 PM
Kalle Moestedt
Kalle Moestedt - avatar