gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:03:55 26 4
gpt4 key购买 nike

以下代码块:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com