Attualmente sto usando una variabile globale nel mio codice chiamato correct
. Considerando che i globals sono disapprovati, c'è un modo migliore per impostare il mio codice per "proteggere" la variabile globale?Python: codice Refactor per rimuovere la variabile globale
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()
È un input e un ritorno da compare_answers()? – Jiminion
Il modo più semplice è quello di allineare 'compare_answers()' a 'game()', e spostare anche la variabile 'correct' in' game() '. – Nayuki
Inoltre, il fatto che tu stia usando la ricorsione di coda in 'game()' e 'compare_answers()' significa che a corto di spazio alla fine. – Nayuki