<p>让我们先来看看你遇到的问题以及如何解决它们</p>
<pre><code>for i in range(3):
testmark = int(input("Enter one test mark: "))
print("Calculating...")
average = (testmark + testmark + testmark) / (i + 1)
print("Your average is", average, "percent.")
</code></pre>
<ol>
<li>每次迭代都重写<code>testmark</code>,这意味着只存储<code>ONE</code>值</li>
<li>您尝试在for循环之外调用<code>i</code>,如果之前未定义<code>i</code>,则调用将失败</li>
</ol>
<p>我们可以调整您的代码,使其更具弹性,并为最终用户提供更多修改函数的能力,例如我们可以如何测试迭代以及我们想要计算的<code>testmarks</code></p>
<pre><code>test_marks = []
tests = int(input('How many tests are there? '))
#How many tests are there? 5
for i in range(tests):
test_marks.append(int(input("Enter one test mark: ")))
#Enter one test mark: 5
#Enter one test mark: 10
#Enter one test mark: 56
#Enter one test mark: 99
#Enter one test mark: 1
print(f"The average test mark is: {sum(test_marks) / len(test_marks)}")
#The average test mark is: 46.5
</code></pre>
<ol>
<li>声明一个空列表以将标记存储为<code>test_marks</code></li>
<li>提示用户定义要输入的测试总数</li>
<li>迭代整个测试并提示用户进行标记</li>
<li>计算并打印平均值(这是Python 3.6+语法!)</li>
</ol>
<p>这是一个很好的机会,可以深入了解Python的一些核心工作原理,我为您的学习提供了一些链接</p>
<p><a href="https://www.geeksforgeeks.org/iterate-over-a-list-in-python/" rel="nofollow noreferrer">Iterating over lists in Python</a>
<a href="https://stackoverflow.com/questions/252703/what-is-the-difference-between-pythons-list-methods-append-and-extend">Appending & extending lists</a>
<a href="https://www.python.org/dev/peps/pep-0498/" rel="nofollow noreferrer">Python 3.6 f-strings</a></p>