我试图增加一个整数的计数,因为if语句返回true。但是,当该程序运行时,它始终打印0.我希望n在程序第一次运行时增加到1。到第二次2等等。
我知道你可以使用全局命令的函数,类和模块,但它不适用于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
编辑:
基于OP对此答案的评论,他想要的是数据持续存在,或者更准确地说,变量
n
在多个运行时间之间保持(或保持它的新修改值)。
所以代码就是(假设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
等许多其他的专用对象序列化模块。
在递增之前打印n
的值。考虑这个修复:
n = 0
print(n)
if True:
n += 1
print(n)
如果您希望它永远运行(请参阅注释),请尝试:
n = 0
print(n)
while True:
n += 1
print(n)
或使用for
循环。
如果您希望它仅与if语句一起使用。我认为你需要放入一个函数并调用自己,我们称之为递归。
def increment():
n=0
if True:
n+=1
print(n)
increment()
increment()
注意:在此解决方案中,它将无限运行。您也可以使用while循环或for循环。