Python Forum

Full Version: Make my codes more simple,
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
Is there a way to write my code more simple, more readable, cleaner. I need all the help I can get. Im headed to germany for a famillie reunion and my flight departs within a few hours, i will be back online as soon as i can get a connection.
import csv

def read():
    a = open("casus.csv", "r")
    areader = csv.reader(a)
    list_to_order = []
    reversed_list = []
    print("score:   team:\n")
    for row in areader:
        if len(row)!=0:
            temp_list = []
            temp_list.append(int(row[1]))
            temp_list.append(row[0])
            list_to_order.append(temp_list)
    list_to_order.sort()
    length = len(list_to_order)
    for i in range (length):
        reversed_list.append(list_to_order[length-1-i])
    for row in reversed_list:
        print (str (row[0])+"      "+row[1])
    input("\n press button to go back to menu")
    menu()

def add():
    team = input("team: ")
    score = input("score: ")

    a = open('casus.csv','a')
    awriter = csv.writer(a)
    awriter.writerow([team,score])
    a.close()
    menu()

def menu():
    answer = input("\n################MENU################\npress 1 to add a team with the scores."
                     "\npress 2 to generate a ranking list\n press 3 to close.  ")

    if answer == "1":
        add()
    elif answer == "2":
        read()
    elif answer == "3":
        exit()
menu()
Hi! here is how to make the read part better
def items_to_order(filename):
    with open(filename, 'r') as infile:
        for row in csv.reader(infile):
            if len(row):
                yield (int(row[1]), row[0])
 
def read():
    print("score:   team:\n")
    list_to_order = sorted(items_to_order('casus.csv'))
    for row in reversed(list_to_order):
        print("{}      {}".format(*row))
    input("\n press button to go back to menu")
    menu()
import csv
 
def read():
    with open("casus.csv", "r") as a:
        areader = csv.reader(a)
        list_to_order = []
        reversed_list = []
        print("score:   team:\n")

        for row in areader:
            if len(row)!=0:
                temp_list = []
                temp_list.append(int(row[1]))
                temp_list.append(row[0])
                list_to_order.append(temp_list)

        list_to_order.sort()
        length = len(list_to_order)

        # for i in range (length):
        #     reversed_list.append(list_to_order[length-1-i])
        
        # you can use reversed function here: for row in reversed(list_to_order):
        for row in reversed(list_to_order):
            print (str (row[0])+"      "+row[1])

        input("\n press button to go back to menu")
        menu()
 
def add():
    team = input("team: ")
    score = input("score: ")
 
    with open('casus.csv','a') as a:
        awriter = csv.writer(a)
        awriter.writerow([team,score])
    # a.close() this is not needed because with statement closed the file automaticaly when the its block of code is executed

    menu()
 
def menu():
    print("""\n################MENU################
              press 1 to add a team with the scores.
              press 2 to generate a ranking list
              press 3 to close.\n""")

    answer = input()
    
    # since the function are first class objects they can be assigned as regular values 
    action = {"1": add, "2": read, "3": exit}

    action[answer]{} # call the function coresponding to the answer
    # if answer == "1":
    #     add()
    # elif answer == "2":
    #     read()
    # elif answer == "3":
    #     exit()

menu()
import csv

def read():
    with open("casus.csv", "r") as f:
        areader = csv.DictReader(f)
        print('\t'.join(areader.fieldnames))
        str_templ = '{{{}}}'.format('}\t{'.join(areader.fieldnames))
        for row in sorted(areader, reverse=True):
            if row:
                print(str_templ.format(**row))
 
def add():
    fields = ['team', 'score']
    user_input = {key:input('{}: '.format(key)) for key in fields}
    with open('casus.csv','a', newline='') as f:
        awriter = csv.DictWriter(f, fieldnames=fields, restval='')
        awriter.writerow(user_input)

    
def menu():
    menu_items = {'1':add, '2':read}
    while True:
        user_choice = input("\n################MENU################\npress 1 to add a team with the scores."
                     "\npress 2 to generate a ranking list\npress 3 to close.\n\n>>")
        try:
            menu_items[user_choice]()
        except KeyError:
            if user_choice == '3':
                break
            else:
                print("This is not a valid choice!\n\n")

if __name__ =='__main__':
    menu()