Sortierung der Ergebnisse und Namen alphabetisch, durchschnittlich, von der höchsten zur niedrigsten

Zurück mit einer weiteren Frage zu meinem Projekt. Deshalb habe ich versucht, meine Ergebnisse in meiner Textdatei in absteigender Reihenfolge zu sortieren. Es wird jedoch ein Syntaxfehler ausgegeben. Der Dateiname wird oben erstellt, wenn der Benutzer den Klassennamen eingibt. Dies entspricht dem Dateinamen. Es wird jedoch ein Fehler ausgegeben.

Dies ist ein Teil meines Codes:

filename = class_name + ".txt"                     
with open(filename, 'a+') as w:                    
    w.write(str(name) + " : " + str(score) + '\n') 
    print("Your results are being updated ...")
    time.sleep(2)
    print("Your score has been updated")
    print("")
    w.close()
if get_bool_input("Do you wish to view the previous results from your class: "): #The 'get_bool_input' will determine if they input yes or no and will either open the file or not.
    selection= input("Do you wish to view the results in Alphabetical order(A), scores highest to lowest(B) or average score highest to lowest?(C)")
    if selection == 'A':
        with open(filename, 'r') as r:
            for name in sorted(r):
                print(name, end='')
    if selection == 'B':
        with open(filename, 'r') as r:
            file_sorted = sorted((ast.literal_eval(x) for x in r),key=lambda z:(int(z[1]),z[0]),reverse=True)        
            r.close()
    if selection not in ['A','B','C']:
        print ("Error, type in A, B or C.")

Wie wird eine Schleife zur Frage 'selection =' ausgeführt? Wenn A, B oder C nicht ausgewählt sind.

if get_bool_input("Do you wish to view the previous results from your class: "): #The 'get_bool_input' will determine if they input yes or no and will either open the file or not.
    selection= input("Do you wish to view the results in Alphabetical order(A), scores highest to lowest(B) or average score highest to lowest?(C)")
    if selection == 'A':
        print (alphabetically(data))
    if selection == 'B':
        print (by_score(data))
    if selection == 'C':
        print (by_average(data))  

    if selection not in ['A','B','C']:
        print ("Error, type in A, B or C.")

else:
    input ("Press any key to exit")

BEARBEITE

Etwas wie das

while True:
    if selection == 'A':
        print (alphabetically(data))
    elif selection == 'B':
        print (by_score(data))
    elif selection == 'C':
        print (by_average(data))  
    return True
    else: selection not in ['A','B','C']:
        print ("Error, type in A, B or C.")

Antworten auf die Frage(2)

Ihre Antwort auf die Frage