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
>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