python 在多行字符串的原始输入时运行时错误
我想要读取多行输入。输入的格式是第一行包含一个整数,表示接下来有多少行字符串。然后我尝试用
while True:
line = (raw_input().strip())
if not line: break
elif line.isdigit(): continue
else:
print line
它打印出了字符串行,但显示了运行时错误的信息。
Traceback (most recent call last):
File "prog.py", line 2, in <module>
line = (raw_input().strip())
EOFError: EOF when reading a line
这样读取输入是对的吗?
为什么会出现运行时错误?
我刚学Python,请帮帮我。
2 个回答
1
你可以这样做:
while True:
try:
number_of_lines = int(raw_input("Enter Number of lines: ").strip())
except ValueError, ex:
print "Integer value for number of line"
continue
except EOFError, ex:
print "Integer value for number of line"
continue
lines = []
for x in range(number_of_lines):
lines.append(raw_input("Line: ").strip())
break
print lines
这样可以处理好输入的数据
6
如果你在程序运行时按下 EOF(在Linux上是 Ctrl-d,在Windows上是 Ctrl-z)来结束程序,你可能会遇到一个叫做 EOFError 的错误。
你可以用下面的代码来捕捉这个错误:
while True:
try:
line = (raw_input().strip())
except EOFError:
break
if not line: break