简体   繁体   中英

Why doesn't my code change when I ask for user input and append that to a list?

I wanna store in a list all user inputs collected over time. I did something like this:

reactions = []
reaction = raw_input("I wanna know your reaction, yo: ")
reactions.append(reaction)

but even after refreshing, my code looks exactly the same, an empty list.

Let's just save them to a file

reaction = raw_input('Please React: ')
with open('reactions.txt', 'a') as f: #a is append mode
    f.write(reaction + '\n')

When I run your code and print reactions I get whatever I entered. If you want to collect a lot of reactions, you could make a loop, which ends once the user enters "q":

 reactions = [] reaction = raw_input("I wanna know your reaction, yo: ") while reaction != "q": reactions.append(reaction) reaction = raw_input("I wanna know your reaction, yo: ") print(reactions) 

I don't know what you mean by "refreshing". But your code creates a new empty list at the beginning, so if you run it again, it will always append to a new empty list. Try to see your code as a list of instructions that execute one after another in sequence.

maybe add at the end a way to show the contents of the list print(reactions) and a loop to repeat the last two lines multiple times:

reactions = []
while True:
    reaction = raw_input("I wanna know your reaction, yo: ")
    reactions.append(reaction)
    print reactions

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM