Thread: Input

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    2
    Rep Power
    0

    Input


    Hi there,

    I am new in Python programming.

    My question is: How to trap the input(user's input)that only text(a,b,c...) allowed. Not number(1,2,3 ...).

    thanks
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,963
    Rep Power
    481
    You don't control which keys the user presses. You can filter/reject/process input.

    For instance, suppose you write code to accept a credit card number. You could accept spaces, hyphens, dots, whatever. Behind the scene your program could remove the non-digits and verify the number.

    Or, commonly, you could change the case of input. Instead of
    Code:
    if 'y' == answer or 'Y' == answer: ok()
    I'd prefer
    Code:
    if 'y' == answer[0].lower(): ok()
    Code:
    '''
        # example
        $ python
        Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
        [GCC 4.7.2] on linux2
        Type "help", "copyright", "credits" or "license" for more information.
        >>> import q
        >>> import string
        >>> q.myprompt('? ',string.ascii_letters+' ',True)
        ? valid input
        'valid input'
        >>>
        >>>
        >>> q.myprompt('? ',string.ascii_letters+' ',True)
        ? valid input?
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
          File "q.py", line 13, in myprompt
            raise ValueError('unacceptable input rejected')
        ValueError: unacceptable input rejected
        >>> 
        >>> 
        >>> 
        >>> q.myprompt('? ',string.ascii_letters+' ',False)
        ? valid input
        'valid input'
        >>> q.myprompt('? ',string.ascii_letters+' ',False)
        ? invalid 823 input
        'invalid  input'
        >>> 
    '''
    
    
    import sys
    
    def myprompt(message,valid_characters,fail):
        sys.stdout.write(message)
        answer = sys.stdin.readline()
        if len(answer):                       # remove new line
            answer = answer[:-1]
        valid = set(valid_characters)
        if set(answer).issubset(valid):
            return answer
        if not fail:
            return ''.join(c for c in answer if c in valid)
        raise ValueError('unacceptable input rejected')
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo