以下代码块:
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' >>>
时间线:
- 2011-02-20 3.2.0 released
- 2011-02-21 issue reported
- 2011-02-23 issue fixed
关于python - 在 while 循环中从键盘读取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7997069/