我无法因EOFError退出,程序因此无限循环
我想做以下几件事:
- 获取用户输入
- 根据输入创建一个列表(前提是这个列表是全新的)
- 把这个列表按字母顺序排序
- 当用户退出程序时,把这个列表用大写字母打印出来,并且每个项目都要编号,从第一个到最后一个。
我有以下代码:
x = input("give me the list: ").capitalize()
#I take the input and put it in all caps
while True:
try:
z = [""]
if x in z:
z = z
else:
z.append(x)
z.sort()
#as long as the user inputs, I keep adding items to the list. If the item is in the list I do not add it, if it I add it
except EOFError:
for i in z:
a = 0
a =+ 1
print(a, i)
#when the user exit the program, I print the item of the list one by one, with a number in front of the item
break
但是我没有得到想要的结果,我卡住了,无法退出程序。系统一直让我输入内容。
比如我输入:“apple”,然后我就一直被要求输入,即使我按了控制键加D也不行。
这是为什么呢?
2 个回答
1
如果不使用整个 while 循环,而是定义一个递归函数来完成程序,就可以完全避免 EOFerror 的出现。
z = []
def f():
global z
x = input("enter values:")
x = x.capitalize()
if x in z:
z = z
else:
z.append(x)
p = input("do u want to insert more values? (Y / N) ")
if p == "Y":
f()
else:
z.sort()
print(z)
f()
希望这对你有帮助 :)
0
如果你的程序需要处理EOFError(文件结束错误),这里有一段代码可能会对你有帮助。
z = []
t=0
def f():
global t
while t==0:
global z
x = input("enter values:")
x = x.capitalize()
if x in z:
z = z
else:
z.append(x)
try:
p = input("do u want to insert more values?(y/n) ")
if p=="y":
f()
else:
z.sort()
print(z)
t=1
except EOFError:
z.sort()
print(z)
t=1
f()
EOFError通常是在没有输入的时候出现的,这个程序会把空输入当作“没有”,然后打印出列表。希望这对你有帮助 :)