
我假设您正在使用python3。
代码的唯一问题是,您从中获取的值
input()是字符串,而不是整数。因此,您需要进行转换。
string_input = input('Question?')try: integer_input = int(string_input)except ValueError: print('Please enter a valid number')现在您将输入作为整数,可以将其与
a
编辑代码:
import randomimport operatorops = { '+':operator.add, '-':operator.sub}def generateQuestion(): x = random.randint(1, 10) y = random.randint(1, 10) op = random.choice(list(ops.keys())) a = ops.get(op)(x,y) print("What is {} {} {}?n".format(x, op, y)) return adef askQuestion(a): # you get the user input, it will be a string. eg: "5" guess = input("") # now you need to get the integer # the user can input everything but we cant convert everything to an integer so we use a try/except try: integer_input = int(guess) except ValueError: # if the user input was "this is a text" it would not be a valid number so the exception part is executed print('Please enter a valid number') # if the pre in a function comes to a return it will end the function return if integer_input == a: print("Correct!") else: print("Wrong, the answer is",a)askQuestion(generateQuestion())欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)