0

Background -

I am attempting to implement some very basis error handling into a function, which accepts integer values (Entities and Views), separated by commas and stored in respective lists.

I have managed to error handle the entities_list using a try and except, by simple printing an error message and then calling the function again (considering its the first user input in the function). However, although I can use else to progress to the user's 2nd input / view_list, I am not sure how to replicate the same error handling, without simply calling the function again, and thus the user has to unnecessarily input into the entities_list again.

Any hints/tips on other blocks to use; I know my code is flawed, I just need some direction with where to research to solve this.

Code -

def user_inputs():
    try:
        entities_list = [int(x) for x in input("Entities for API Call:\n").split(', ')]
    except:
        print("---ERROR: MUST BE COMMA SEPERATED VALUES---")
        user_inputs()
    else:
        views_list = [int(x) for x in input("Views for API Call:\n").split(', ')]
        print("Must be comma seperated integer values")
user_inputs()
William
  • 191
  • 5
  • 32
  • 1
    you can't write `else` without an `if` before it. `else` is not connected to the `try` statement. please see [python documentation](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) – jsofri Nov 11 '21 at 06:03
  • 1
    Also don't call the same function from your `except` clause. You are causing unintended recursion. – Selcuk Nov 11 '21 at 06:03
  • @jsofri else is connected to try statements. The else block will be executed when there's no exception occured in try block. You can search on internet for more reference –  Nov 11 '21 at 07:20
  • @abhijitShirwal do you have a reference for that? – jsofri Nov 11 '21 at 07:36
  • @jsofri I'm not able to paste the link here, but if you search on google, you'll get answer from SO itself. https://stackoverflow.com/questions/855759/python-try-else –  Nov 11 '21 at 09:42

1 Answers1

0

I was able to solve my problem as follows -

def user_inputs():
while True:
    try:
        entities_list = [int(x) for x in input("Entities for API Call:\n").split(', ')]
    except ValueError:
        print("---ERROR: MUST BE COMMA SEPERATED VALUES---")
        continue
    break
while True:
    try:
        views_list = [int(x) for x in input("Views for API Call:\n").split(', ')]
    except ValueError:
            print("---ERROR: MUST BE COMMA SEPERATED VALUES---")
            continue
    break
user_inputs()

Many thanks for all the input and advice!

William
  • 191
  • 5
  • 32