Break 'while loop' while handling exceptions. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Break 'while loop' while handling exceptions.

I'm trying to do a program that iterates over the keys of a dictionary, if the key is in the dictionary, it will print the value of that key. If the key is not in the dictionary the exception block executes and display an error message, however, I want to break the loop if the user input is empty, my problem is that the exception block takes that action too. The code looks something like this: try: … number = int(input()) if number == '': break if number in dictionary: … except ValueError: print('Error!') Can anyone, please, help me?

7th Aug 2016, 8:40 PM
Francisco Gómez García
Francisco Gómez García - avatar
3 Answers
0
The int(input()) will raise a value error when it attempts to convert the empty string to an integer. There's no way around that. Undefined keys raise KeyError and not ValueError. Again however, if you are using an if statement to check if the key exists, then the error won't be raised. To get the error to be raised, directly print the value of the key without checking that the key exists.
7th Aug 2016, 10:02 PM
Gershon Fosu
Gershon Fosu - avatar
0
No, Gershon. Dictionaries can still use integer values as keys, just like list use integers for indexes, but they don't have to start at 0 and can be any number. In my case, that's necessary; that's why I have to convert the user input from string to integer... However, what you said about converting an integer to an empty string... well, that make me think. Maybe that's the problem.
7th Aug 2016, 10:29 PM
Francisco Gómez García
Francisco Gómez García - avatar
0
Oops. Just ignore that part then xd. Read everything else. Btw values in a dictionary are never stored in the order you put them so trying to put them in order like you mentioned may not give you the order you want.
10th Aug 2016, 6:02 AM
Gershon Fosu
Gershon Fosu - avatar