You miss the lines
if grade != -1:
numbers.append(grade)
after grade = int(grade)
. This adds the grade to the list numbers
.
Review
- Use PEP8 (you can use pep8online.com) to check your code
- For unnamed input, I prefer
"Largest is %i, smallest is %i" % (max(numbers), min(numbers))
- You can use
sum
to sum up integers in a list - If you add a shebang (the first line
#!/usr/bin/env python
), then Linux users can execute your script directly like this:./yourscript.py
instead ofpython yourscript.py
.
Code
I would rather write the code like this:
#!/usr/bin/env python
def get_grades():
"""Return a list of grades."""
numbers = []
while True:
grade = int(input("Enter grade, -1 to end: "))
if grade != -1:
numbers.append(grade)
else:
return numbers
if __name__ == '__main__':
grades = get_grades()
if len(grades) != 0:
average = float(sum(grades)) / len(grades)
print('Largest is %i, smallest is %i.' % (max(grades), min(grades)))
print("Class average is %0.2f." % average)
Reading error messages
You probably had the following:
$ python test.py
Enter grade, -1 to end:1
Enter grade, -1 to end: 2
Enter grade, -1 to end: 3
Enter grade, -1 to end: -1
Traceback (most recent call last):
File "test.py", line 15, in <module>
print('Largest is {}, smallest is {}'.format(max(numbers), min(numbers)))
ValueError: max() arg is an empty sequence
Now you should first look for line number. This one says in line 15
is something wrong. This is:
print('Largest is {}, smallest is {}'.format(max(numbers), min(numbers)))
Now you have to investigate further. What exactly is wrong? What could possibly go wrong in this line?
Now you read
ValueError: max() arg is an empty sequence
That should look strange, because you checked gradeCounter != 0
. Next, you would print the contents of the argument of max. This is empty, so adding to the list numbers
did not work.
2
solved Python looping code