-2

Top of my code

player_name = input('Please enter your first and last name: ')

player_class = input('Please enter your class. {Class 1, Class 2 or Class 3}: ')

player_class = "N:\General homework\Computer Science\Class Files\\" + 
player_class + '.txt'

Bottom of my code

average_score = (int(score_1) + int(score_2) + int(score_3)) / 3

write_to_file = player_name + ' ' + str(score_1) + "/10" + ' ' + str(score_2) + "/10" + ' ' + str(score_3) + "/10" + ' Average is ' + str(round(average_score))
 + "/10" + "\n"

file = open(player_class,"a")

file.write(write_to_file)

file.close()

I've been searching for a while, and I have no idea how to alphabetically sort this. If i were to input the name as Ben and class as Class 1, then as Alice and Class 1, it would still show Ben first. Ive tried the sorted{} function and it just doesnt work. I need this for an assessment and have no idea what to do! Please help if you can :(

2
  • 1
    You are overwriting the value of the player_class variable with the file path. Also, you only seem to write a single line of text to your file. What's there to sort? Can you give the expected output? Jun 2, 2015 at 8:44
  • I am trying to make it so each time it I run the code and it adds a new line to the text file, It will also sort the whole file at the same time. This means when there are multiple lines it should sort them. If i were to say one person was called Ben and another Alice, it would come out as Ben, 0/10 0/10 0/10 (Its a maths quiz those are the scores) Alice, 0/10 0/10 0/10 Then, I want it to sort the file so Alice goes first. Jun 2, 2015 at 8:51

1 Answer 1

0

You need to keep the players in memory in some kind of data structure, e.g. a list.

Once you have a list containing the things you want to sort, then you can use sorted() to alphabetize it, and then use the sorted list to write all of the players to a file in order.

1
  • ok, I think I can do that. Thanks! That makes a lot more sense than what im trying to do! Jun 2, 2015 at 8:48

Your Answer

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

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