【问题标题】:Raw_Input is not ending the prompt after I hit enterRaw_Input 在我按回车后没有结束提示
【发布时间】:2017-06-17 19:05:24
【问题描述】:

我正在尝试使用此函数从标准输入中获取一个字符,并且 raw_input 在我按 Enter 后不会结束提示。我可以按我喜欢的次数按回车键,它不会移动到下一行。

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

我也从this question.获取了这段代码

我在 Ubuntu 16.04 上使用 python 2.7.12。

【问题讨论】:

    标签: python-2.7 raw-input


    【解决方案1】:

    如果我运行你的代码

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

    它完全符合我的预期。你会得到不同的结果(如果是,那是什么?)还是你期待别的结果(如果是这样,那又是什么?)。您所说的“在我按 Enter 后不会结束提示”是什么意思并不完全清楚。如果您希望您的函数在您只按回车键以响应提示时返回,那么这一行

    if len(u_Input) == 1:
    

    需要改变。如果你只是按回车,那么len(u_Input) 将为零。

    【讨论】:

    • ...发现错误。我输入的值导致程序退出 while 循环,而不是在需要时退出。不过感谢您的帮助!
    猜你喜欢
    • 2022-10-13
    • 2011-04-01
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    相关资源
    最近更新 更多