使用try / except,如果我们不能转换为int,它将设置is_dig
为False
:
try:
int(question)
is_dig = True
except ValueError:
is_dig = False
if is_dig:
......
def is_digit(n):
try:
int(n)
return True
except ValueError:
return False
if is_digit(question):
....
首先查看您对int的编辑转换,检查输入是否为数字,然后转换无意义,请一步一步完成:
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
不知道Z的在做,但一切 Z = Z + 0
是一样的没有做任何事情来Z
在所有1 + 0 == 1
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")