use*_*391 4 python loops enter input exit
所以我一直在读一下如何通过用户按下回车键退出while循环,我想出了以下内容:
import sys, select, os
switch = 1
i = 1
while switch == 1:
os.system('cls' if os.name == 'nt' else 'clear')
print "I'm doing stuff. Press Enter to stop me!"
print i
while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = raw_input()
if not line:
print "Finished! =]"
switch = 0
else:
print "Finished! =]"
switch = 0
i = i+1
Run Code Online (Sandbox Code Playgroud)
有没有办法整理一下?特别是"if not line"和下面的"else"看起来很乱.它们可以组合成一个吗?使用"开关"的更好的替代方案?
最初,如果我键入一堆字符,然后点击输入,它就不会停止循环.我必须再次按回车键.if not和else组件旨在将其设置为在第一次按Enter时退出.
这对我有用:
import sys, select, os
i = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print "I'm doing stuff. Press Enter to stop me!"
print i
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = raw_input()
break
i += 1
Run Code Online (Sandbox Code Playgroud)
您只需要检查输入的stdin一次(因为第一个输入将终止循环).如果条件行/非行有结果,则可以将它们组合到一个if语句中.然后,只使用一个while语句,您现在可以使用break而不是设置标志.