数学游戏不起作用 [英] 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 reason, whenever you input the answer, the program says it's wrong, even if the answer is right.
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")
推荐答案
您可以使用literal_eval(来自ast内置函数)来代替int.如果将来要支持浮点数,则可以使用浮点数或整数.您还需要一些异常处理,以防用户输入字符串或仅按Enter键.
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
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")
这篇关于数学游戏不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!