1

I am trying to create an exception handling into a loop .

I have created the below code and I would like to put an exception in userId1 and userid2.

For example, the total amount of users is 943, so when the user enters an userId which is greater than 943, to put an exception with a message 'Sorry, this userId does not exist' and to start the loop over again.

I tried to do it with the try: and except KeyError: but didn't play correct or I didn't write in appropriate order.

How can I write it?

exit=False
while exit is False:
    print("Hello Lady or Gentleman, this is a very primitive movie recommnedation system, please follow the instructions below : ")
    print("---------------------------------------------------------------------------")
    print("1) If you would like to find the difference 1 please press 1")
    print("2) If you would like to find the difference 2 please press 2")
    print("3) If you would like to exit, then press 0")

    option=False
    while option is False:
        print("Εnter what would you like to find please :",end=" ")
        option=input();
        if option =='1':
            print("The total number of users is 943, so you should enter 2 user_ids lower than 944")
            print('---------------------')
            print("Enter the first userId please :",end=" ")
            user1 = input();
            print("Enter the second userId please :",end=" ")
            user2 = input();
        elif option == '2':
            print("The total number of movies is 1682, so you should enter 2 movie_ids lower than 1683")
            print('-------------------')
            print("Enter the first bookId please :",end=" ")
            bookId1 = input();
            print("Enter the second bookId1 please :",end=" ")
            bookId2= input();
        elif option == '0':
            exit = True
            print("Thank you very much")
            break
        else:
            option = False
            print("This option is not valid, Please try again!")
Cœur
  • 37,241
  • 25
  • 195
  • 267
notis
  • 23
  • 4
  • 1
    Related: [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) ... [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – wwii Nov 29 '19 at 23:43
  • btw you can get rid of those semicolons, in fact it's recommended – wjandrea Nov 29 '19 at 23:46

3 Answers3

3

Use the continue statement return to the start of the loop.

if int(user1) > 943:
    print('Sorry, this userId does not exist')
    continue
Irfan434
  • 1,463
  • 14
  • 19
  • Thank you very much – notis Nov 29 '19 at 23:41
  • Note that this will return to the outer loop. See [How to continue in nested loops in Python](https://stackoverflow.com/questions/14829640/how-to-continue-in-nested-loops-in-python). – Irfan434 Nov 29 '19 at 23:43
  • Yes, i just noticed that after the continue statement goes to elif statement – notis Nov 29 '19 at 23:47
2

Exceptions stop execution - i.e. they make your program close. You cannot continue to loop after raising an exception. As well, it doesn't make any sense to handle an exception that you raise from the same scope (except in advanced cases).

I suspect what you're actually trying to do is print an error if the input is invalid. For that, see Asking the user for input until they give a valid response. You would want to put the validation while loop inside the if option == blocks, something like this:

if option == '1':
    while True:
        user = int(input('User: '))
        if user > 943:
            print('There are only 943 users!')
            continue
        else:
            break
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • I don't want to continue the loop, I want to start over again, – notis Nov 29 '19 at 23:44
  • @notis Start again from where? – wjandrea Nov 29 '19 at 23:48
  • print("Enter the first userId please :",end=" ") 4 If the user gives an UserId greater that 943 i want to start it again and to ask him again – notis Nov 29 '19 at 23:51
  • @notis Yes, that's exactly what I'm recommending in the second paragraph – wjandrea Nov 29 '19 at 23:52
  • @notis I clarified the wording of the first paragraph btw, to make it clear that raising an exception makes the program close – wjandrea Nov 29 '19 at 23:53
  • @wjandreaif user1 > 943: print('This userId is does not existd') else: I wrote it like above and plays correct – notis Nov 29 '19 at 23:57
  • But, in case that I enter an UserId lower that 943, for example 100, the loop start over again, does not got to the second option – notis Nov 30 '19 at 00:08
1

I don't see the try and except statement in your code block. Did you remove that?

In order for a try/except statement to do something, an error needs to be raised. You could raise the KeyError exception yourself.

I think you'll need something along the lines of:

if userID > 943:
    raise KeyError(userID)

More info on raising exceptions here: https://docs.python.org/3/tutorial/errors.html#raising-exceptions

user1558604
  • 947
  • 6
  • 20