Menu

Input Validation

Range Checks

A range check confirms that a numeric value lies between a lower limit and an upper limit. The boundary values are normally counted as valid, so a rule of 1 to 6 accepts both 1 and 6.

Imagine booking seats at a small cinema where each row has 6 seats, so the software only allows a group of 1 to 6 people. Nobody books 0 seats, and 7 people would not fit in the row. The check tests the number against both limits and rejects anything outside them.

Seats enteredInside 1 to 6?Result
0NoRejected
1YesAccepted
6YesAccepted
7NoRejected

The comparison operators decide what happens at the edges. A condition written as seats >= 1 and seats <= 6 keeps both boundaries. Using > 1 and < 6 instead would wrongly reject a booking for 1 or for 6.

The rule must match the real data

A range that is too narrow rejects valid values: allowing only 2 to 5 seats would refuse a person booking alone or a family of six who should be accepted. A range that is too wide lets impossible values through: 0 to 100 seats would accept a booking for 60 people when the row only has 6 seats, and the booking would fail later. The limits should come from the real situation, not from a guess.

Range checks suit anything with sensible limits, such as a percentage from 0 to 100, a month number from 1 to 12, or a quantity of stock items.

The rule goes straight into a condition. The answer is converted to an integer so it can be compared with the limits.

seats = int(input("How many seats do you want? "))

if seats >= 1 and seats <= 6:
    print("Booking accepted")
else:
    print("Please enter a number from 1 to 6")

Output when the user types 7:

How many seats do you want? 7
Please enter a number from 1 to 6

Practise this