1

i want to limit the users input in two cases:

1.With a string and split, when asking the user to put in two, 2 digit numbers I wrote:

x=raw_input("words").split()

I want to only enable him to write an input that is two 2 digit numbers, and if he does something else I want to pop an error, and for him to be prompted again, until done right.

2.This time an INT when asking the user for a random 4 digit number:

y=int(raw_input("words"))

I only want to allow (for example) 4 digit numbers, and again if he inputs 53934 for example I want to be able to write an error explaining he must only enter a 4 digit number, and loop it back until he gets it right.

Thank you, hopefully I explained myself properly.

update so - trying to start simple i decided that at first ill only try to ask the user to type in 8 letters. for example an qwertyui input is acceptable, but sadiuso (7 chars) is not.

so i tried working with the syntax you gave me and wrote:

y=raw_input("words") if not (len(y) == 8):
    pop an error

but im getting a syntax error on the :

0

1 Answer 1

2

Use str.isdigit and len

>>> '12345'.isdigit()
True
>>> 'ab12'.isdigit()
False
>>> len('12')
2

while True:
    x = raw_input('Input 2 digits: ')
    if x.isdigit() and len(x) == 2:
        x = int(x)
        break
    print('input should be 2 digits.')

print('x = {}'.format(x))
Sign up to request clarification or add additional context in comments.

10 Comments

ok i need a LITTLE more help here, even though this is a huge step in the right direction, would you mind showing me how exactly to input that into my code? still very new to this.
@Giladiald, Put if statement after the raw_input line.
@falsetru, why use an if instead of an assert? I'm under the impression assert is more Pythonic by asking for forgiveness later..
@falsetru, thanks, I had my suspicions about using assert which is why I asked, but how about a try-except? Maybe performance wise it'd be better to assume a correct input and catch a bad one..
|

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.