使用try / except,如果我们不能转换为int,它将设置
is_dig为
False:
try: int(question) is_dig = Trueexcept ValueError: is_dig = Falseif is_dig: ......
或做一个功能:
def is_digit(n): try: int(n) return True except ValueError: return Falseif 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")


