我目前在我的代码中使用一个名为correct
. 考虑到全局变量不受欢迎,有没有更好的方法来设置我的代码来“保护”全局变量?
from random import randint
from random import choice
lower = int(raw_input("Enter a lower integer constraint: "))
higher = int(raw_input("Enter a higher integer constraint: "))
correct = 0
def gen_randoms(lower, higher):
integers = list()
for x in xrange(4):
rand_int = randint(lower, higher)
integers.append(rand_int)
return integers
def gen_equation(integers):
nums = map(str, integers)
operators = ['*', '+', '-']
equation = 'num op num op num op num'
while 'op' in equation:
equation = equation.replace('op', choice(operators), 1)
while 'num' in equation:
equation = equation.replace('num', choice(nums), 1)
print equation
return equation
def evaluate(equation):
answer = eval(equation)
print answer
return answer
def compare_answers(gen_answer, game):
global correct
user_answer = int(raw_input("What is the answer? "))
if user_answer == gen_answer:
correct += 1
print 'Correct!'
print 'Current streak: %s' % str(correct)
game()
else:
print 'Incorrect!'
correct = 0
game()
def game():
nums = gen_randoms(lower, higher)
this_equation = gen_equation(nums)
gen_answer = evaluate(this_equation)
compare_answers(gen_answer, game)
game()