How to check if a number is in a given interval using python ?

Published: July 26, 2020

Tags: Python;

DMCA.com Protection Status

Examples of how to check if a number is in a given interval using python:

Check if a number is in an closed interval

Let's assume for example that that the goal is to test if x is in the closed interval [2, 6], example with x = 1:

>>> x = 1
>>> 2 <= x <= 6
False

example with x = 3:

>>> x = 3
>>> 2 <= x <= 6
True

example with x = 2:

>>> x = 2
>>> 2 <= x <= 6
True

Check if a number is in an open interval

open interval ]2, 6[, example with x = 2

>>> x = 2
>>> 2 < x < 6
False

Check if a number is in an half-open interval

Half-open interval t ]2, 6], example with x = 6

>>> x = 6
>>> 2 < x <= 6
True

example with x=2

>>> x = 2
>>> 2 < x <= 6
False

References