To check if number is in range(x,y)

Tim Chase python.list at tim.thechases.com
Mon Dec 14 20:50:56 EST 2020


On 2020-12-14 21:21, Schachner, Joseph wrote:
> >>> r = range(10)  
> So r is a list containing 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

In Python 3.x, r is *not* a list.  It is a custom object/class.

>   >>> 2 in r  
>   True
> As expected.

I'm not sure what your replies are suggesting here.  I demonstrated
the OP's edge-cases, especially cases that one might experience coming
from other languages.

>   >>> r = range(1, 10, 2)
>   >>> 2 in r  
>   False
>   >>> list(r)  
>   [1, 3, 5, 7, 9]
> Well, yes, because you started the range at 1.  Start at 0 and
> you'd get 0, 2, 4, 6, 8.

Had I done this, for pedagogical value I would have checked for 3
then:

  >>> r = range(0, 10, 2)
  >>> 3 in r
  False

The goal was to demonstrate that the resulting range object, when
given a step-size of something than the default 1, will have holes in
it, and as such, testing for membership in one of those holes would
fail.  Showing successful membership wouldn't add any value.

> "It also doesn't automatically convert from the string inputs
> you're getting from the input() function:
> 
>   >>> s = "5"
>   >>> s in r  
>   False
>   >>> int(s) in r  
>   True"
> You have just discovered that Python, although it is dynamically
> typed, is STRICTLY typed. 

No, not just now discovered something I've long known.  The goal was
to provide an example for the OP of this exact case since their
original code attempted to use the string returned from input() and
used it as-is (without converting to int) for this exact sort of
comparison.

> Another way to say this: you have discovered that Python isn't the
> same as BASIC.

Additionally, (many? all? some?) BASICs have similarly strict typing.
For example, reaching for the BASIC that I used in the 80s:

  ] S$ = "HELLO"
  ] I = 42
  ] PRINT S$ + I
  ?TYPE MISMATCH ERROR

> "Additionally, note that the endpoint of the range is exclusive so
>   >>> r = range(1, 10)
>   >>> 10 in r  
>   False"
> 
> I don't have to note that

My comment was directed at the OP.  Unless you are Bischoop, that's
not you.

> Now suppose that the end integer was not excluded. Each range call
> would produce 11 integers. 

The goal was to show the OP that while some languages (such as the
aforementioned BASIC) have *inclusive* ranges:
  
  ] FOR I = 1 to 3 : PRINT I : NEXT
  1
  2
  3

Python's ranges are exclusive.  Because a language could have either,
the example demonstrated Python's choice.

> I recommend you read Python 101 and when you've done that, read
> Python 201.   I think they are very good "learn Python" books. If
> you're surprised that the end point is not included in range, you
> need to read Python 101.

Your condescending replies bark up the wrong tree.

-tkc








More information about the Python-list mailing list