1

My code all works and the List works but for some reason when I try to sort it , the list doesn't sort to ascending order but instead a random order.So while the list changes it doesn't to descending order. When I tried the x.sort(reverse=True) an error message popped up saying it couldn't be in integer form. Can anyone help me?

score=input('What is your score?')
Scorefile=open('score.txt','a')
Scorefile.write(score)
Scorefile.write("\n")
Scorefile.close()
Scorefile = open('score.txt','r')
with open('score.txt','r') as Scorefile:
     scores=Scorefile.readline()
     List=[]
     while scores:
           scores2=(scores.strip())
           int(scores2)
           List.append(scores2)
           scores=Scorefile.readline()
List.sort()
print(List)
#Output(not in ascending order)
['12', '12', '12', '12', '12', '13', '15', '17', '4', '5', '6']
1
  • 3
    it's sorted lexographically, if you want it sorted as integers you need to specify that or convert to integers Commented Oct 9, 2019 at 20:13

2 Answers 2

3

Your elements are strings (type str), not integers (type int). Your code currently seems to be sorting by lexographical order.

Try converting your elements to ints before sorting. Change these lines in your code:

int(scores2)
List.append(scores2)

to this:

List.append(int(scores2))

The statement int(scores2) on a line on its own does not do anything useful, you have to use the output of int().

Sign up to request clarification or add additional context in comments.

Comments

2

It's not sorting numbers, it's sorting strings. As strings of characters, they are sorted.

You can solve this by changing this line

        int(scores2)

to this.

        scores2 = int(scores2)

Right now you are converting the value to an integer, but not actually using that integer anywhere. I think that is where the confusion is coming from.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.