Skip to content Skip to sidebar Skip to footer

Math Game Not Working

I made a function for a program I am making, It's a math game where you have to input an answer, and if the answer is right you win. I thought the game was simple, but for some rea

Solution 1:

Instead of int, you could use literal_eval (from the ast built-in). That will allow either a float or an int in case you want to support floats in the future. You'd also want some exception handling in case the user enters a string or just hits Enter.

Then, you'll want to loop until the user gets it right. One possible fix would be:

import random
from ast import literal_eval

defgameChoice():
    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)

        whileTrue:
            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:
                    breakelse:
                    print("sorry, try again")

        print("congrats, you got it right")

Solution 2:

The code:

player_answer is a string

and

answer is an int

which makes the 2 never equal to each other try putting

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

this makes the input automatically a integer

Post a Comment for "Math Game Not Working"