Home > Back-end >  Cannot get out of infinite loop
Cannot get out of infinite loop

Time:05-14

The problem I am trying to solve is go through a list. In this list, if there is the letter "a", give me all those words. Once I have done that, pose the same question again so I go choose the letter "m". Once I type "quit" give me the final list.

Here is the code I have so far, but I get stuck in an infinite loop. I am missing something small that prevents me from asking the same question. When I type the below code, I get an infinite loop.

list = ["aardvark", "baboon", "camel", "elephant", "python", "giraffe", "tiger", "gorilla"]
     
new_list = []

y = input("Pick an orange letter that you want to check against.  Type quit to exit  ") 


while y != "quit":
    for x in list:
        if y in x:
            new_list.append(x)
    print(new_list)

CodePudding user response:

You are not asking for new input in your loop. Therefore, you are not updating your value of y necessary to exit the loop.

Something like the below should work.

list = ["aardvark", "baboon", "camel", "elephant", "python", "giraffe", "tiger", "gorilla"]
 
new_list = []

y = input("Pick an orange letter that you want to check against.  Type quit to exit  ") 


while y!= "quit":
 for x in list:
     if y in x:
      new_list.append(x)
 print(new_list)
 y = input("Pick an orange letter that you want to check against.  Type quit to exit  ") 

CodePudding user response:

You answered you own question: you did not let the user type the question again! Correct the code like this:

    list = ["aardvark", "baboon", "camel", "elephant", "python", "giraffe", "tiger", "gorilla"]

    new_list = []

    y = input("Pick an orange letter that you want to check against.  Type quit to exit  ") 


    while y!= "quit":
    for x in list:
        if y in x:
            new_list.append(x)
    y = input("Pick an orange letter that you want to check against.  Type quit to exit  ") 
    print(new_list)
  • Related