0

hope you're doing well. I'd like to ask you people a question I hope you will help me, since I am a beginner and I don't know where else to ask these things, I know here there are a lot of good programmers who can try to help me, thanks. I'd like to create a program when I ask the user what is your name they enter it and then the name gets added into the list automatically, so next time when I do print list the name I entered should be in that list.

list_names = ["James", "John", "Sarah", "Tina"]
print(list_names)
add_name = input("Enter your name: ")
list_names.append(add_name)
print(list_names)

So when I do print(list_names) it gives me the name of the list, when I ask user to enter another name, the name gets added, but when I exit the program and do again print(list_names) the name is not in there. Can you give me any idea, please ?

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
olloshka
  • 1
  • 2
  • In nut shell you should use extra storage for your list_names, at this moment all happens in memory and clean after exit from the program. – Brown Bear Aug 20 '22 at 15:09
  • Can you please explain more about this please Brown ? – olloshka Aug 20 '22 at 15:10
  • You'll want to either add a database (probably overkill to just store a list of strings) or save the contents of your list to some sort of file (pickle, or text). – jorf.brunning Aug 20 '22 at 15:10
  • See the duplicate, especially [this answer](https://stackoverflow.com/a/59586116/550094) using JSON – Thierry Lathuille Aug 20 '22 at 15:10
  • If you want data to persist between program runs, you will need some sort of data storage outside of your .py file. Probably the easiest thing to do right now would be to save your data to a `.json` file, which you load and write to every time you run the program. You can check out this question for more detail: https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file – C_Z_ Aug 20 '22 at 15:11
  • list_names = ["James", "John", "Sarah", "Tina"] print(list_names) add_name = input("Enter your name: ") list_names.append(add_name) print(list_names) with open("file.txt", "w") as f: for s in list_names: f.write(str(s) + "\n") list_names = [] with open("file.txt", "r") as f: for line in f: list_names.append(str(line.strip())) – olloshka Aug 20 '22 at 15:18
  • I used this but still not getting added – olloshka Aug 20 '22 at 15:18
  • you should add code to question. It will be more readable and more people will see it. – furas Aug 21 '22 at 08:58
  • your code makes no sense. You have to read data from file at the beginning of code and write data to file at the end (eventually when you get new data). – furas Aug 21 '22 at 08:59

0 Answers0