pythonloopsexcept

I cannot exit with EOFerror, and hence the program continues endlessly


I am trying to do the following:

I have the following code:

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

Instead of getting such a result, I am stuck and cannot exit the program. I keep being asked for inputs.

For example I write: "apple", and I am then asked again and again, even if U press control-d.

Why?


Solution

  • In case the EOFError needs to be a part of the program, here's a code that might help.

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

    As EOFError is generally used when input is not provided, this program will take a blank input as "no" and print the list. hope this helped :)