Ross Ross - 7 months ago 30
Python Question

add user input to list

I want it to ask the user to input their favorite film and it to add that input at the end of the list and then display the list again. as well as making sure the film entered is not in the least already. this is how far ive got up to :

films = ["Star Wars", "Lord of the Rings", "Shawshank Redemption", "God father"]

for films in films:
print ("%s" % films)

add = input("Please enter a film: ")
films.insert(-1,add)
print (films)


Edit:

When I tried that I get an error:


Traceback (most recent call last):

File "H:\Modules (Year 2)\Advanced programming\Python\Week 2 -
Review and Arrays\Week 2.2 - Exercises.py", line 48, in
films.append(add)
AttributeError: 'str' object has no attribute 'append'

Answer

Use in to check whether the item is already present in list or not and then use list.append to add that item to the end of the list.

add = input("Please enter a film: ")
if add not in films:
    films.append(add)

Note that in the for-loop you've replaced films with a string, use some other variable name:

for film in films:
    print ("%s" % film)