Lets start by taking a look at the issues you encountered and how you can address them;
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.")
- You override
testmark
every iteration, meaning you only ever store ONE
value
- You attempt to call
i
outside of the for loop, which will fail if i
is not defined prior
We can adjust you code to be more resilient and provide the end-user more ability to modify the functions, such as how may iterations we test and the testmarks
we would like to calculate.
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
- Declare an empty list to store marks in as
test_marks
- Prompt the user to define the total tests being entered
- Iterate over the total tests and prompt the user for a mark
- Calculate and print the average (This is Python 3.6+ Syntax!)
This is a good opportunity to dive a little deeper to bolster your understanding of some core workings on Python, i have included a few links for your learning!
Iterating over lists in Python
Appending & extending lists
Python 3.6 f-strings