我无法因EOF错误退出,因此程序会无休止地继续

问题描述 投票:0回答:1

我正在尝试执行以下操作:

  • 获取用户的输入
  • 根据输入创建一个列表(仅当这是原始列表时)
  • 按字母顺序对列表进行排序
  • 用户退出程序后,以大写字母打印列表,每个项目从第一个到最后一个编号。

我有以下代码:

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”,然后我就会一次又一次地被问到,即使你按下 control-d。

为什么?

python loops except
1个回答
0
投票

如果程序在没有 while 循环的情况下完成,通过为其定义一个递归函数,可以完全避免 EOF 错误。

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()

希望有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.