# Viewing test scores from one of three CSV files

Is there any way I could tidy this code and make it look better and more appealing?

import csv
math_class = input ("Which math class would you like to see the results of?")
while math_class not in ['1','2','3']:
math_class = input ("Which math class would you like to see the results of?")
sort = input ("How would you like to sort the results alphabetical, highest or average:\n")
while sort not in ["alphabetical","highest","average"]:
sort = input ("How would you like to sort the results")
class_file_names = ['Class 1.csv', 'Class 2.csv', 'Class 3.csv']
scan = open(class_file_names[int(math_class)-1], 'r+')
data = []
next(scan)

for row in rows:
data.append(row)
scan.close()

if(sort == "alphabetical"):
word = "- Highest Score on test:"
sorted_= sorted(data, key=lambda name: name [0])
field = 5

if(sort == "average"):
word = "- Average Score"
sorted_ = sorted(data, key=lambda average: average[4], reverse=True)
field = 4

if(sort == "highest"):
word = "- Highest Score on test:"
sorted_ = sorted(data, key=lambda total: total[5], reverse=True)
field = 5

for row in sorted_:
print(str(row[0]), word, str(row[field]))
input ("Sort Complete, press any key to close the program.")


If there is no way I could clean up the code, then that's fine as it does what I want it to (it's just that I thought the code could look more appealing than it already is).

## migrated from stackoverflow.comApr 26 '16 at 14:37

This question came from our site for professional and enthusiast programmers.

• Maybe correct indentation? – linusg Apr 25 '16 at 20:00
• @linusg I have to try to keep it small – Video Assets Apr 25 '16 at 20:02
• Yh, it sorts the data that another code writes and improves the formats of the data to however the user wants to sort the data – Video Assets Apr 25 '16 at 20:05
• @zondo ty sorry for posting this in the wrong part of stackoverflow – Video Assets Apr 25 '16 at 20:10

If you see a whole bunch of if/else statements with the only difference being some function, take advantage of the fact that functions are first class objects in python. For instance, you could create a dictionary that maps your sort options to sorting functions; while you're at it, explore the built ins (such as operator) as well:

from operator import itemgetter

sort_options = {
# itemgetter(0) is equivalent to lambda x: x[0]
# >>> x = [1, 2, 3]
# >>> f = itemgetter(0)
# >>> g = itemgetter(1)
# >>> f(x)
# 1
# >>> g(x)
# 2
# sort_option: (key_of_sort, your_word, sort_in_reverse?, your_field)
'alphabetical': (itemgetter(0), "- Highest Score on test:", False, 5),
'average': (itemgetter(4), "- Average Score", True, 4),
'highest': (itemgetter(5), "- Highest Score on test:", True, 5),
}

def custom_sort(data, sort):
fn, word, rev, field = sort_options[sort]
sorted_ = sorted(data, key=fn, reverse=rev)
return word, sorted_, field

word, sorted_, field = custom_sort(data, sort)

• ty for the advice and it works well with my code, although now when it displays the averages it does it in reverse order. How do I fix this. Also sorry if I seem like a noob at python. I'm really new to Python @Bahrom – Video Assets Apr 25 '16 at 20:38
• @VideoAssets, whoops, try edited answer – Bahrom Apr 25 '16 at 20:42
• ty @Bahrom , my code works great now – Video Assets Apr 25 '16 at 20:46
• @VideoAssets no worries, I just added some comments with an example of itemgetter. In general, if you find yourself retyping the same lines over and over again, pause and think about what you're trying to accomplish. Good luck with Python, it's a fun language to learn! – Bahrom Apr 25 '16 at 20:54

First of all, remove 4 spaces at the beginning of each line (Or is this just wrong indented in the SO editor?). What I recommend is to split up the code into logical parts and put empty lines between them, e.g.:

import csv

math_class = input ("Which math class would you like to see the results of?")

while math_class not in ['1','2','3']:
math_class = input ("Which math class would you like to see the results of?")

sort = input ("How would you like to sort the results alphabetical, highest or average:\n")

while sort not in ["alphabetical","highest","average"]:
sort = input ("How would you like to sort the results")

class_file_names = ['Class 1.csv', 'Class 2.csv', 'Class 3.csv']
scan = open(class_file_names[int(math_class)-1], 'r+')
data = []
next(scan)
...


import csv
math_class = input ("Which math class would you like to see the results of?")
while math_class not in ['1','2','3']:
math_class = input ("Which math class would you like to see the results of?")
sort = input ("How would you like to sort the results alphabetical, highest or average:\n")
while sort not in ["alphabetical","highest","average"]:
sort = input ("How would you like to sort the results")
class_file_names = ['Class 1.csv', 'Class 2.csv', 'Class 3.csv']
scan = open(class_file_names[int(math_class)-1], 'r+')
data = []
next(scan)


Another thing is, functions should be written like this:

myfunc(arg)


and not

myfunc (arg)


which you're using in the last line:

input ("Sort Complete, press any key to close the program.")


Everything else is fine!

• ty for the input however I might refrain from splitting the code up as I have to keep it as small as possible. – Video Assets Apr 25 '16 at 20:12
• No, not splitting it up, sorry that was meaned not like splitting the code to several files. Just empty lines after a while loop here and there, to make the code more readable. – linusg Apr 25 '16 at 20:14

Adding on to what has already been said, for this an future projects you may want to consider making several smaller functions and calling them, rather than the approach you take now. Additionally, you could apply the PEP8 standard(https://www.python.org/dev/peps/pep-0008/). There are tools available to check this for you; one example is the IDE PyCharm. Finally, a good practice to integrate into you coding in general is to look for "code smells" and avoid them.(http://blog.codinghorror.com/code-smells/)

• ty for the input @Albert , I will try to consider the factors you mentioned and apply PEP8 standard in future projects. – Video Assets Apr 25 '16 at 20:48