-1

I need to allow the user to input only numbers from 1111 to 9999 as raw_input in python. How do I create a constraint for this condition? Thanks

hs7624
  • 693
  • 2
  • 10
  • 20
  • 1
    with a while loop ? – Benjamin Jun 24 '16 at 12:02
  • similar question: http://stackoverflow.com/questions/8761778/limiting-python-input-strings-to-certain-characters-and-lengths – Shubham Jun 24 '16 at 12:06
  • 1
    Do you know how to check if a number is between two other numbers? – Padraic Cunningham Jun 24 '16 at 12:10
  • By "number" do you mean an integer `int` or a real number `float` or something else? – Rory Daulton Jun 24 '16 at 12:13
  • 1
    Look at the accepted answer in [this question](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response). You would then use `num = sanitized_input('Type a number from 1111 to 9999:', int, 1111, 9999)`. I now use that function for my own programs. – Rory Daulton Jun 24 '16 at 12:25

4 Answers4

2

Get the input then check if the input is valid to your constraint (e.g. via an if condition). If it is not valid repeat the input (probably with notifiyng the user what was wrong with the input before) (e.g. with a while loop).

syntonym
  • 7,134
  • 2
  • 32
  • 45
0

You cannot force the user to input any specific thing using raw_input(). You'll have to validate the user input and preferably use a while loop until user enters correctly.

This will work (assuming the user is not stupid to input non-digits).

i = int(raw_input('Please, enter a number between 1110 and 10000'))
while not(1110<i<10000):
  i = int(raw_input('Dude, come on, read the instruction'))
Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
0

Use a while loop until the user inputs a valid number. Check for ValueError to eliminate invalid input.

user_input = -1
_continue = True
while _continue:
    try:
        user_input = int(raw_input("Value: "))
        if 1111 <= user_input  <= 9999:
            _continue = False
    except ValueError:
        pass
Zroq
  • 8,002
  • 3
  • 26
  • 37
0
is_input_valid = False
while is_input_valid == False:
    inp = int(raw_input("Input your number: "))
    if inp >= 1111 and inp <= 9999:
        is_input_valid = True
    else:
        print "Please input only numbers from 1111 to 9999"

print "Thanks, your input is valid"