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

Try/Except handling

Today i made this function to try and understand the try/except.
If i run this code it should ask for a positive integer x, to roll a dice function x times.
I made the code below but it seems to never get in the "ValueError". I’d like to check if the input (n) is first an integer (digit in the string) and secondly if the integer is positive. if one of these occur, raise the exception.

How can i fix it that it works correctly?

def userInput():
    while True:
        try:
            n=input("How many times do you want to roll the dice? ")
            if not n.isdigit():
                raise TypeError
            
            n = int(n)
            if n < 0:
                raise ValueError
            else:
                break

        except ValueError:
            #if type is integer but not a positive integer
            print("Please enter a positive integer")
    
        except TypeError:
            #if type is not an integer
            print("Only positive integers allowed")
    
return n

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 :

Your code works perfectly for positive numbers, to handle negative numbers, you need to modify at one place

if not n.lstrip('-').isdigit():

I hope this solves your problem

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