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

标签 python loops input keyboard python-3.x

以下代码块:

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

最佳答案

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

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

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

时间线:

关于python - 在 while 循环中从键盘读取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7997069/

相关文章:

jquery - "Clickable" Canvas 驱动的翻页演示中的链接和文本输入

python - Python : Alert if more than N errors in a given period? 日志解析

javascript - 如何删除 for 循环的第一部分?

Java 猜数游戏问题

java - 如何在java中旋转一定数量的单词

html 类型编号不会重新定位

python - 列出所有 Pipenv 环境

python - 在 Python 中禁用全局变量查找

python - 在python中按句子结构对文本进行分类

java - 有没有办法做到这一点,这样我就没有 64 个 if 语句?