0

I'm a high school computer science teacher, and my original background is in java, jquery, javascript, etc. Not Python. Which I'm required to teach here.

I've been trying to figure out this if/else statement in a larger bit of code, but my lack of knowledge of Python is catching up with me. (Please do not recommend I start with Scratch. The district decided to have it blocked just before the school year started, and I have to teach code.)

The code looks like this (there's more to it if you'd like):

def set_message(students):
    if students.sort(reverse=True):
        message = "Your students are in reverse order"
    else:
        message = "Your students are in alphabetical order"
    students.sort()
    show_students(students, message)
    students.sort(reverse=True)
    show_students(students, message)

I suspect that if statement is what's getting me here. If you have any ideas, I'd love to hear them and hear why they work.

Ms.K
  • 1
  • What do you think the `sort` method should return? Try it on the interactive console. Does it return what you expected? – Mechanic Pig Sep 08 '22 at 18:28
  • The code you posted is incorrect. `list.sort()` does not return anything so the `if students.sort(revers=True)` will always be false. – treuss Sep 08 '22 at 18:28
  • If `students` is a list, its `sort` method will sort it in place and always return `None`, which is False in boolean context, so the test will always fail. So, this code doesn't really make sense... – Thierry Lathuille Sep 08 '22 at 18:29
  • 1
    Please check [this question](https://stackoverflow.com/questions/3755136/pythonic-way-to-check-if-a-list-is-sorted-or-not) for how to check, whether a list is sorted or not. – treuss Sep 08 '22 at 18:31
  • The `if` makes no sense at all. In your two calls to `show_students()`, one will definitely be in alphabetical order (because you just sorted the list) and one will be in reverse order (because you just sorted the list in reverse); there is nothing conditional about it. – jasonharper Sep 08 '22 at 18:32

0 Answers0