0

I'm new to programming/Python. I'm trying to create a function that will add a word to a list. I tried to use a while loop to add ask if the user wants to add another word. If the user inputs 'y' or 'Y' I want to run the function again. If the user inputs anything else, I want the function to return the list. When I run the function, it continues to run the function again no matter what is input. Please help. Thanks

def add_list():
    x = []
    first_list = raw_input('Please input a word to add to a list ')
    x.append(first_list)
    response = raw_input('Would you like to enter another word ')
    while response == 'y' or 'Y':
        add_list()
    else:
        return x

2 Answers 2

4
while response == 'y' or 'Y':

Should be

while response == 'y' or response == 'Y':

or better yet:

while response in ('y', 'Y'):

Here's why what you did doesn't work. Each line below is equivalent.

while response == 'y' or 'Y'
while (response == 'y') or ('Y')
while (response == 'y') or True
while True
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. I revised the while portion to what you suggested and I still doesn't work correctly. It continues to loop if I input anything other than 'y' or 'Y'. Am I missing something?
@user1816629: Should be if, not while
1

Just make the list a parameter you pass to the function:

x = []
add_list(x)

With add_list(x)

def add_list(x):
  first_list = raw_input('Please input a word to add to a list ')
  x.append(first_list)
  response = raw_input('Would you like to enter another word ')
  while response in ('y', 'Y'):
    add_list(x)
  else:
    return

2 Comments

I don't think this is the problem OP mentioned.
You are right on the infinite loop part but his current return is still a problem which he'll be facing once he solved the infinite loop. Edited the loop condition according to Eric's answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.