0
\$\begingroup\$

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+')
rows = csv.reader(scan)
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).

\$\endgroup\$
4
  • \$\begingroup\$ Maybe correct indentation? \$\endgroup\$
    – linusg
    Apr 25, 2016 at 20:00
  • \$\begingroup\$ @linusg I have to try to keep it small \$\endgroup\$ Apr 25, 2016 at 20:02
  • \$\begingroup\$ 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 \$\endgroup\$ Apr 25, 2016 at 20:05
  • \$\begingroup\$ @zondo ty sorry for posting this in the wrong part of stackoverflow \$\endgroup\$ Apr 25, 2016 at 20:10

3 Answers 3

5
\$\begingroup\$

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)
\$\endgroup\$
4
  • \$\begingroup\$ 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 \$\endgroup\$ Apr 25, 2016 at 20:38
  • \$\begingroup\$ @VideoAssets, whoops, try edited answer \$\endgroup\$
    – Bahrom
    Apr 25, 2016 at 20:42
  • \$\begingroup\$ ty @Bahrom , my code works great now \$\endgroup\$ Apr 25, 2016 at 20:46
  • \$\begingroup\$ @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! \$\endgroup\$
    – Bahrom
    Apr 25, 2016 at 20:54
0
\$\begingroup\$

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+')
rows = csv.reader(scan)
data = []
next(scan)
...

instead of

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+')
rows = csv.reader(scan)
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!

\$\endgroup\$
2
  • \$\begingroup\$ ty for the input however I might refrain from splitting the code up as I have to keep it as small as possible. \$\endgroup\$ Apr 25, 2016 at 20:12
  • \$\begingroup\$ 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. \$\endgroup\$
    – linusg
    Apr 25, 2016 at 20:14
0
\$\begingroup\$

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/)

\$\endgroup\$
1
  • \$\begingroup\$ ty for the input @Albert , I will try to consider the factors you mentioned and apply PEP8 standard in future projects. \$\endgroup\$ Apr 25, 2016 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.