Answer a question

when I try this

if question.isdigit() is True:

I can type in numbers fine, and this would filter out alpha/alphanumeric strings

when I try 's1' and 's' for example, it would go to (else).

Problem is, when I put negative number such as -1, '.isdigit' counts '-' sign as string value and it rejects it. How can I make it so that '.isdigit' allows negative symbol '-'?

Here is the code. Of the thing i tried.

while a <=10 + Z:
    question = input("What is " + str(n1) + str(op) + str(n2) + "?")
    a = a+1

    if question.lstrip("-").isdigit() is True:
        ans = ops[op](n1, n2)
        n1 = random.randint(1,9)
        n2 = random.randint(1,9)
        op = random.choice(list(ops))

        if int(question) is ans:
            count = count + 1
            Z = Z + 0
            print ("Well done")
        else:
            count = count + 0
            Z = Z + 0
            print ("WRONG")
    else:
        count = count + 0
        Z = Z + 1
        print ("Please type in the number")

Answers

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")
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐