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

84 Views Asked by At

I am trying to do the following:

  • Get input from the user
  • Create a list from the input (only if this an original one)
  • Sort the list alphabetically
  • Once the user exit the program, print out the list in capital letters, with each item being numbered from first to last.

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?

2

There are 2 best solutions below

1
sampriti On BEST ANSWER

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

4
sampriti On

The EOFerror can be avoided completely if the program is done without the while loop as a whole, by defining a recursive function for the same.

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

hope it helped :)