擅长:python、mysql、java
<p>不要使用<code>eval</code>。如果希望用户提供整数,请使用<code>int</code>。你知道吗</p>
<p>然后将<code>count</code>变量移到循环外,以避免在每次迭代时重新创建新的<code>count</code>变量,并将值重置为零。你知道吗</p>
<pre><code>def game(n):
count = 0
for _ in range(n):
a = int(input('Enter a number:'))
b = random.randrange(0,10)
print(a,'+',b,'=')
answer = int(input('Enter your answer:'))
result = a + b
if answer != result:
print('Incorrect')
else:
count = count + 1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
</code></pre>
<p>当用户输入不是整数时,<code>int</code>的使用也将帮助您正确处理异常。见<a href="https://docs.python.org/2/tutorial/errors.html" rel="nofollow noreferrer">Handling exceptions</a>。你知道吗</p>
<p>关于使用<code>eval</code>:<a href="https://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice">Is using eval in Python a bad practice?</a></p>