数学游戏不起作用

时间:2018-05-08 19:32:08

标签: python math

我为我正在制作的节目制作了一个函数,这是一个数学游戏,你必须输入答案,如果答案是对的,你就赢了。我认为游戏很简单,但出于某种原因,无论何时输入答案,程序都会说错了,即使答案是对的。

def gameChoice():
    print("what game do you want to play? A math game")
    game_choice = input(">>")
    if game_choice == 'math game':
        number1 = random.randint(1, 30)
        number2 = random.randint(1, 30)
        answer = (number1 + number2)
        print("%d + %d = %d" %(number1, number2, answer))
        player_answer = input(">> ")
        if player_answer == answer:
            print("congrats, you got it right")

        else:
            print("sorry, try again")

2 个答案:

答案 0 :(得分:0)

代码:

player_answer is a string 

answer is an int 

这使得2永远不会相互试图放

player_answer = int(input(">> "))

这会使输入自动为integer

答案 1 :(得分:0)

而不是int,你可以使用literal_eval(来自内置的ast)。如果你想在将来支持浮点数,那将允许float或int。如果用户输入字符串或只是按Enter键,您还需要一些异常处理。

然后,您将要循环,直到用户正确为止。一个可能的解决方案是:

import random
from ast import literal_eval

def gameChoice():
    print("what game do you want to play? A math game")
    game_choice = input(">>")
    if game_choice == 'math game':
        number1 = random.randint(1, 30)
        number2 = random.randint(1, 30)
        answer = (number1 + number2)

        while True:
            print("%d + %d = %d" % (number1, number2, answer))
            try:
                player_answer = literal_eval(input(">> "))
            except ValueError:
                print('Please enter a number for the answer')
            except SyntaxError:
                print('Please enter an answer')
            else:
                if player_answer == answer:
                    break
                else:
                    print("sorry, try again")

        print("congrats, you got it right")