假设 if 语句返回 true,我正在尝试增加整数的计数。然而,当这个程序运行时,它总是打印 0。我希望程序第一次运行时 n 增加到 1。第二次到2等等。
我知道函数、类和模块可以使用 global 命令,在它之外,但这不适用于 if 语句。
n = 0
print(n)
if True:
n += 1
最佳答案
根据上一个答案的评论,你想要这样的东西吗:
n = 0
while True:
if True: #Replace True with any other condition you like.
print(n)
n+=1
编辑:
Based on the comments by OP on this answer, what he wants is for the data to persist or in more precise words the variable
n
to persist (Or keep it's new modified value) between multiple runs times.
所以代码如下(假设 Python3.x):
try:
file = open('count.txt','r')
n = int(file.read())
file.close()
except IOError:
file = open('count.txt','w')
file.write('1')
file.close()
n = 1
print(n)
n += 1
with open('count.txt','w') as file:
file.write(str(n))
print("Now the variable n persists and is incremented every time.")
#Do what you want to do further, the value of n will increase every time you run the program
注意:
对象序列化的方法有很多种,上面的例子是最简单的一种,您可以使用专用的对象序列化模块,如 pickle
等。
关于python - 在 python 中使用 if 语句有条件地增加整数计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49062852/