在 while 循环中从键盘读取字符

发布于 2024-12-13 15:19:20 字数 1532 浏览 1 评论 0原文

以下代码块:

ans = 'x'
while ans not in ['Y','y','N','n']:
    ans = input("Do Something? [y|n]:")
    print(ans in ['Y','y','N','n'])

产生以下输出:

Do Something? [y|n]:Y
False
Do Something? [y|n]:y
False
Do Something? [y|n]:N
False
Do Something? [y|n]:n
False
Do Something? [y|n]:asdf
False
Do Something? [y|n]:Traceback (most recent call last):
  File "./NumberPatterns.py", line 27, in <module>
    ans = input("Do Something? [y|n]:")
KeyboardInterrupt

我想重复读取用户的输入,直到它是“Y”,“y”,“N”,“n”。 但循环永远不会停止。一定有什么东西是我遗漏的。 请帮我。

编辑:
在交互模式下运行时,这是相同代码的相同结果: Windows 7 计算机上的版本为 3.2.0。

C:\Users\jwalker>python
Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> ans = 'x'
>>> while ans not in ['Y','y','N','n']:
...     ans = input("Do Something? :")
...     print(ans in ['Y','y','N','n'])
...     print(ans, type(ans), len(ans), ord(ans[0]), repr(ans))
...     print('Y', type('Y'), len('Y'), ord('Y'), repr('Y'))
...
Do Something? :asdf
False
 <class 'str'> 5 97 'asdf\r'
Y <class 'str'> 1 89 'Y'
Do Something? :Y
False
 <class 'str'> 2 89 'Y\r'
Y <class 'str'> 1 89 'Y'
Do Something? :n
False
 <class 'str'> 2 110 'n\r'
Y <class 'str'> 1 89 'Y'
Do Something? :Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
>>>
>>> ^Z

The following block of code:

ans = 'x'
while ans not in ['Y','y','N','n']:
    ans = input("Do Something? [y|n]:")
    print(ans in ['Y','y','N','n'])

produces the following output:

Do Something? [y|n]:Y
False
Do Something? [y|n]:y
False
Do Something? [y|n]:N
False
Do Something? [y|n]:n
False
Do Something? [y|n]:asdf
False
Do Something? [y|n]:Traceback (most recent call last):
  File "./NumberPatterns.py", line 27, in <module>
    ans = input("Do Something? [y|n]:")
KeyboardInterrupt

I want to read the user's input repeatedly, until it is 'Y','y','N','n'.
But the loop never stops. There must be something that i am missing.
Please help me.

EDIT:
This is the same result of the same code, when run in Interactive Mode:
Version is 3.2.0 on a Windows 7 machine.

C:\Users\jwalker>python
Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> ans = 'x'
>>> while ans not in ['Y','y','N','n']:
...     ans = input("Do Something? :")
...     print(ans in ['Y','y','N','n'])
...     print(ans, type(ans), len(ans), ord(ans[0]), repr(ans))
...     print('Y', type('Y'), len('Y'), ord('Y'), repr('Y'))
...
Do Something? :asdf
False
 <class 'str'> 5 97 'asdf\r'
Y <class 'str'> 1 89 'Y'
Do Something? :Y
False
 <class 'str'> 2 89 'Y\r'
Y <class 'str'> 1 89 'Y'
Do Something? :n
False
 <class 'str'> 2 110 'n\r'
Y <class 'str'> 1 89 'Y'
Do Something? :Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
>>>
>>> ^Z

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

白芷 2024-12-20 15:19:20

将您的 Python 更新到更新版本。

您遇到了 3.2.0 中引入的错误,并且几乎立即修复了。从错误报告来看:

在 Python 3.2 中,内置函数 input() 返回一个带有
Windows 上的尾随“\r”:

C:\Python32>python
Win32 上的 Python 3.2(r32:88445,2011 年 2 月 20 日,21:29:02)[MSC v.1500 32 位(Intel)]
输入“帮助”、“版权”、“制作人员”或“许可证”以获取更多信息。
>>>>>打印(repr(输入()))
测试
'测试\r'
>>>>>

时间线:

Update your Python to a more recent version.

You have run afoul of a bug that was introduced in 3.2.0 and almost immediately fixed. From the bug report:

In Python 3.2, the builtin function input() returns a string with a
trailing '\r' on windows:

C:\Python32>python
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print(repr(input()))
test
'test\r'
>>>

Time line:

隱形的亼 2024-12-20 15:19:20

该代码在 Python 3.2 中运行得很好:

>>> ans = 'x'
>>> while ans not in ['Y','y','N','n']:
...    ans = input("Do Something? [y|n]:")
...    print(ans in ['Y','y','N','n'])
Do Something? [y|n]:y
True
>>>

这让我怀疑你的问题比你的基本示例更复杂。你在哪里运行代码?它是在循环内部的函数中吗?

That code works perfectly well in Python 3.2:

>>> ans = 'x'
>>> while ans not in ['Y','y','N','n']:
...    ans = input("Do Something? [y|n]:")
...    print(ans in ['Y','y','N','n'])
Do Something? [y|n]:y
True
>>>

This makes me suspect that your question is a hint more complicated than your basic example. Where are you running the code? Is it in a function which is inside of a loop?

小ぇ时光︴ 2024-12-20 15:19:20

编辑此答案适用于 Python-2,因此这不是回答标有 Python-3.x 的问题。请不要考虑它。


根据 Python 文档,您应该使用 raw_input()

考虑使用 raw_input() 函数来处理用户的一般输入。

那是因为 input() 不是您所期望的:

输入([提示])

相当于 eval(raw_input(prompt))。

正如您的评论所强调的那样,这并不是您真正需要的。

EDIT This answer is for Python-2, so this is not answering to a question tagged with Python-3.x. Please do not consider it.


According to Python documentation, you should use raw_input():

Consider using the raw_input() function for general input from users.

That's because input() is not what you expect:

input([prompt])

Equivalent to eval(raw_input(prompt)).

This is not really what you need here, as highlighted by your comment.

祁梦 2024-12-20 15:19:20

尝试使用 strip() 修剪文本:

ans = 'x'
while ans.strip() not in ['Y','y','N','n']:
    ans = raw_input("Do Something? [y|n]:")
    print(ans.strip() in ['Y','y','N','n'])

try trimming the text with strip():

ans = 'x'
while ans.strip() not in ['Y','y','N','n']:
    ans = raw_input("Do Something? [y|n]:")
    print(ans.strip() in ['Y','y','N','n'])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文