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
"-"is not a digit, so you raise theTypeErrorbefore you reach the next check.isdigitis the wrong check anyway. You can check this with the superscript 2.'²'.isdigit()is true, butint('²')will fail. You might want to read "Digits int() doesn’t dig"