Raw_Input is not ending the prompt after I hit enter

I am trying to take one character from the stdin using this function and raw_input will not end the prompt after I hit enter. I can hit enter as many times as I'd like and it will not move onto the next line.

def userInput():
    print "What would you like to do?"
    while True:
            u_Input = raw_input(':')
            if len(u_Input) == 1:
                    break
            print 'Please enter only one character'
    return u_Input

I also took this code from this question.

I'm using python 2.7.12 on Ubuntu 16.04.

1 answer

  • answered 2017-06-17 19:05 BoarGules

    If I run your code

    Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> def userInput():
    ...     print "What would you like to do?"
    ...     while True:
    ...             u_Input = raw_input(':')
    ...             if len(u_Input) == 1:
    ...                     break
    ...             print 'Please enter only one character'
    ...     return u_Input
    ...
    >>> userInput()
    What would you like to do?
    :53
    Please enter only one character
    :57
    Please enter only one character
    :a
    'a'
    >>>
    

    it does exactly what I expect. Do you get different results (if so, what?) or do you expect something else (and again, if so, what?). It's not exactly clear what you mean by "will not end the prompt after I hit enter". If you expect your function to return when you hit only the enter key in response to the prompt, then this line

    if len(u_Input) == 1:
    

    needs to change. If you just hit enter, then len(u_Input) will be zero.