Simplficando chained comparisons

Asked

Viewed 49 times

3

According to pycharm (which is with the default settings for pep8) says it is possible to simplify this line.

        elif student['averange'] >= 5 and student['averange'] < 7:
            student['situation'] = 'Recuperação'

inserir a descrição da imagem aqui

  • I find it curious that people who don’t have enough knowledge of language to understand what the answer might be give a negative vote to the question. It is not because you do not know that there are not all elements that allow the correct answer in the question, and it is admits a correct answer, quietly.

  • I changed the title to make it more generic and more people can get to the question

1 answer

5


Because Python has a very cool comparison Feature that allows more than one comparison to the same element to be written in the same notation that we use in mathematics. So, if we want to know if a number is between "5" and "7", instead of writing "if x > 5 and x < 7", as we think when programming, we can write "if 5 < x < 7", as we do in mathematics. Internally, Python turns it into "5 < x and x < 7".

Your line would then look like this:

elif 5 <= student['averange'] < 7:
  • Has some Python version restriction?

  • 1

    No - this has worked for a long time, at least since Python 2.2

  • Gee, I didn’t know, interesting I’ll start using it now ;)

  • Interesting, I didn’t know you could do this! How the conversion is done?

  • 4

    It’s actually done by the Python compiler directly. When he finds a < x < b, he internally duplicates the value of x, keeps this copy, compares it to < x, if it is true, then compares x < b, otherwise he notes the result as false. (internally the code used for "and" is not even used - the two comparisons are made directly in sequence)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.