Cameron Burrows - 4 months ago 25

Python Question

So i'm not exactly sure how to ask this question exactly but basically I want to see if any value between two variables is also in between two other variables. So for instance here is a sample of what code might look like of what I'm explaining

`var1 = 0`

var2 = 20

var3 = 5

var4 = 15

if var3 <= [any value in range var1 to var2] <= var4:

do something

so that's basically it, but I'm not sure what would go in place of the brackets or if there is another way to do it. Sorry if there's an easy solution, I'm pretty tired. Thanks!

Answer

Let's use a bit of mathematical notation. So you have two number ranges, [*a*, *b*] and [*x*, *y*], where [*a*, *b*] represents the concept of "all numbers between *a* and *b*".

One interpretation is you want to see if [*a*, *b*] is a **subset** of [*x*, *y*].

```
if x <= a and b <= y:
...
```

Another is that you want to see if [*a*, *b*] **intersects** [*x*, *y*] in any way. That happens when either of the two endpoints *a* or *b* is contained within [*x*, *y*], or vice versa.

```
if ((x <= a <= y or x <= b <= y) or
(a <= x <= b or a <= y <= b)):
...
```