How to type negative number with .isdigit?

If you do not wish to go for try... except, you could use regular expression

if re.match("[+-]?\d", question) is not None:
    question = int(question)
else:
    print "Not a valid number"

With try... except, it is simpler:

try:
    question = int(question)
except ValueError:
    print "Not a valid number"

If isdigit is must and you need to preserve the original value as well, you can either use lstrip as mentioned in an answer given. Another solution will be:

if question[0]=="-":
    if question[1:].isdigit():
        print "Number"
else:
    if question.isdigit():
        print "Number"

Use lstrip:

question.lstrip("-").isdigit()

Example:

>>>'-6'.lstrip('-')
'6'
>>>'-6'.lstrip('-').isdigit()
True

You can lstrip('+-') if you want to consider +6 a valid digit.

But I wouldn't use isdigit, you can try int(question), it'll throw an exception if the value cannot be represented as int:

try:
    int(question)
except ValueError:
    # not int

Use a try/except, if we cannot cast to an int it will set is_dig to False:

try:
    int(question)
    is_dig = True
except ValueError:
    is_dig = False
if is_dig:
  ......

Or make a function:

def is_digit(n):
    try:
        int(n)
        return True
    except ValueError:
        return  False

if is_digit(question):
   ....

Looking at your edit cast to int at the start,checking if the input is a digit and then casting is pointless, do it in one step:

while a < 10: 
     try:
        question = int(input("What is {} {} {} ?".format(n1,op,n2)))
     except ValueError:
        print("Invalid input")
        continue # if we are here we ask user for input again

    ans = ops[op](n1, n2)
    n1 = random.randint(1,9)
    n2 = random.randint(1,9)
    op = random.choice(list(ops))

    if question ==  ans:
        print ("Well done")
    else:
        print("Wrong answer")
    a += 1

Not sure what Z is doing at all but Z = Z + 0 is the same as not doing anything to Z at all 1 + 0 == 1

Using a function to take the input we can just use range:

def is_digit(n1,op,n2):
    while True:
        try:
            n = int(input("What is {} {} {} ?".format(n1,op,n2)))
            return n
        except ValueError:
            print("Invalid input")


for _ in range(a):
    question = is_digit(n1,op,n2) # will only return a value when we get legal input
    ans = ops[op](n1, n2)
    n1 = random.randint(1,9)
    n2 = random.randint(1,9)
    op = random.choice(list(ops))

    if question ==  ans:
        print ("Well done")
    else:
        print("Wrong answer")

Tags:

Python