Kushal Sonigra
Kushal Sonigra

Reputation: 17

How can I validate if a variable is between two specified numbers?

How can I validate user input to restrict them in only entering numerical values between -5 and -21? I currently have this while loop set up;

while True: 
 if flatNumber.isdigit():
      flatNumber = int(flatNumber)
      if flatNumber>5 and flatNumber<21: 
           print("Enjoy your stay.") 
           break 
      else:  
           flatNumber = input("Please enter your flat number.")
 else: 
    flatNumber = input("Please enter a numerical flat number.")

However this only validates numerical values between 5 and 21? Can someone please post a solution and explain it as to how I can validate numerical values between -5 and -21?

Upvotes: 1

Views: 121

Answers (5)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You can use a simplified chained comparison using negative values:

if -21 < flatNumber < -5:

str.isdigit won't work for negative numbers, you should almost always use a try/except when validating input:

while True:
    try: 
        # try to cast to int
        flatNumber = int(input("Please enter your flat number."))
        # if cast was successful make sure it is in range if not ask again
        if not -21 < flatNumber < -5:
            print("Not in range -5 to -21")
            continue
        break # else all is good break the loop
    except ValueError:
           print("Invalid input")

print(flatNumber)

Upvotes: 2

Mohamed Ramzy Helmy
Mohamed Ramzy Helmy

Reputation: 269

modify this line like

if flatNumber<-5 and flatNumber>-21: 

Upvotes: 0

Bonga Mbombi
Bonga Mbombi

Reputation: 175

if flatNumber>-21 and flatNumber<-5:

Remember that -5 is greater than -21.

Upvotes: 0

James Cochran
James Cochran

Reputation: 29

Can you not just change the numbers and the directions of the inequalities? Like so:

if flatNumber<-5 and flatNumber>-21:

Upvotes: 1

Astra Bear
Astra Bear

Reputation: 2738

If you want exclusive test like you +5 to +21:

if flatNumber<-5 and flatNumber>-21: 
           print("Enjoy your stay.") 
           break 
      else:

If you want inclusive test

if flatNumber<=-5 and flatNumber>=-21: 
           print("Enjoy your stay.") 
           break 
      else:

Upvotes: 0

Related Questions