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
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.