-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

5
  • 1
    with a while loop ? Commented Jun 24, 2016 at 12:02
  • similar question: stackoverflow.com/questions/8761778/… Commented Jun 24, 2016 at 12:06
  • 1
    Do you know how to check if a number is between two other numbers? Commented Jun 24, 2016 at 12:10
  • By "number" do you mean an integer int or a real number float or something else? Commented Jun 24, 2016 at 12:13
  • 1
    Look at the accepted answer in this question. 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. Commented Jun 24, 2016 at 12:25

4 Answers 4

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).

Sign up to request clarification or add additional context in comments.

Comments

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'))

Comments

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

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.