Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Make my codes more simple,
#1
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()
Reply
#2
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()
Reply
#3
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()
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
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()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How would you (as an python expert) make this code more efficient/simple coder_sw99 3 1,755 Feb-21-2022, 10:52 AM
Last Post: Gribouillis
  make a costume subploting from separate codes avihu 0 1,207 Aug-30-2020, 05:01 PM
Last Post: avihu
  Iterate through all files in a folder and make simple calculation danielappleton 2 2,266 Apr-01-2020, 09:57 AM
Last Post: danielappleton
  How to make a simple automation process of login using "if condition" soimba 3 2,717 Jan-07-2020, 11:58 PM
Last Post: SheeppOSU
  Python Program to Make a Simple Calculator jack_sparrow007 2 10,099 Oct-19-2018, 08:32 AM
Last Post: volcano63
  make a simple list larri 3 2,896 Jul-20-2018, 12:25 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020