0

I came across an answer that we can check if number is between a given range by following method 10<=n<=100. I want to know how exactly this statement gets executed in python.I'm new to python and know how to code in java.

From the answers, I came to know that this feature is called chaining comparison operators. Thanks a lot for answers.

2 Answers2

3

this is 'how exactly this statement gets executed'

import dis

def f(n):
    return 10<=n<=100

print(dis.dis(f))

which gives

  6           0 LOAD_CONST               1 (10)
              3 LOAD_FAST                0 (n)
              6 DUP_TOP
              7 ROT_THREE
              8 COMPARE_OP               1 (<=)
             11 JUMP_IF_FALSE_OR_POP    21
             14 LOAD_CONST               2 (100)
             17 COMPARE_OP               1 (<=)
             20 RETURN_VALUE
        >>   21 ROT_TWO
             22 POP_TOP
             23 RETURN_VALUE

but did you really want to know that?

Chaining comparison operators may be a good reference.

It's really translating into 10 < n and n < 100

Graham
  • 7,431
  • 18
  • 59
  • 84
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
1

In python, these kind of double conditions are executed as consecutives ands, so:

10 <= n <= 100

is equal to:

(10 <= n) and (n <= 100)

And it returns a boolean that can either be True or False depending on whether the statement is met.

ebeneditos
  • 2,542
  • 1
  • 15
  • 35