Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Alternative to try: something(), except: pass

Here is my code, it takes 2 input parameters, and asks the user to re-input until the input isn’t 1 or 2.

def inputParams(x,y):
    while True:
        try:
            x = int(input(y))
            if x == 1 or x == 2:
                return x
            else:
                print("Invalid Input")
                inputParams(x, y)
        except ValueError:
            pass

It works perfectly fine, but as I have heard using

try: 
    something()
except:
    pass

is a bad habit, I want to know if there is an alternative solution to this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Skip the recursion, and use the ValueError to continue the loop before checking the integer value.

def inputParam(prompt):
    while True:
        x = input(prompt)
        try:
            n = int(x)
        except ValueError:
            print("Invalid integer input")
            continue

        if n == 1 or n == 2:
            return n

        print("Enter 1 or 2")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading