Home > Back-end >  Python Exception handling in less lines
Python Exception handling in less lines

Time:05-23

I am having a lot of exception statement in my code block and I need to shorten the code to 100 lines. Is there a better way with less lines to write one of my exception codes below?

while True: 
    try:
        difficulty = int(input("Choose level 1: Easy  2: Difficult): "))
        if (difficulty!=1 and difficulty!=2):
            raise ValueError # this will send it to the print message
        break
    except ValueError:
        print("Please enter the right value")

Kind regards

CodePudding user response:

[...] with less lines to write one of my exception codes below?

Not exactly... but you can shorten it by one line if you want:

while (difficulty!=1 and difficulty!=2):

This will make useless the raise and the if statement.

CodePudding user response:

difficulty = int(input("Choose level (1: Easy  2: Difficult): "))
while (difficulty!=1 and difficulty!=2):
    print("Please enter the right value")
    difficulty = int(input("Choose level (1: Easy  2: Difficult): "))

CodePudding user response:

If keeping the exception handling makes sense in your case, you could remove the raise statement and just catch ValueError instead

while True:
    try:
        difficulty = int(input("Choose level (1: Easy  2: Difficult): "))
        if difficulty == 1 or difficulty == 2:
            break
    except ValueError:
        print("Please enter the right value")
  • Related