I'm pretty new to programming and having difficulty understanding exactly what happens at program runtime. My question relates to this bit of code in Python:
list1 = []
input_from_user = input("Enter word: ")
list1.append(input_from_user)
for i in list1:
print(i)
Why is it that every time I run the program, the list1 variable seems to refresh itself? In other words, if I run the program once and input 'Hello' when prompted, then run the program a second time and input 'World', the program only outputs 'World' after the second run. Why doesn't the list1 variable grow in size by 1 word each time I run the program, instead of 'forgetting', so to speak, what happened the last time I ran the program? Is there a way to define or store variables in such a way that they maintain the value they had at the conclusion of the previous runtime?
答案 0 :(得分:1)
"程序每次运行时都清除所有变量吗?"
是
您会看到,每次运行程序时,它都会再次设置变量。
A = 0
A = A + 1
变量A以值0开始,然后以1递增。如果再次运行程序,A将设置为0,然后递增1。
程序并不一定清除变量,可以说,但实际上并没有将它们存储在任何地方。当你启动程序时,每次都会创建一个新变量,当程序结束时,变量就会消失。
如果您想存储变量的值,我建议您查看Pickle模块。