Alb*_*ang 2 python if-statement global-variables python-3.x
考虑到if语句返回true,我正在尝试增加整数的计数。但是,当该程序运行时,它总是打印0。我希望n在第一次运行时增加到1。到第2次,依此类推。
我知道可以使用global命令的函数,类和模块可以使用它,但这不适用于if语句。
n = 0
print(n)
if True:
n += 1
Run Code Online (Sandbox Code Playgroud)
您n在递增之前打印值。考虑此修复程序:
n = 0
print(n)
if True:
n += 1
print(n)
Run Code Online (Sandbox Code Playgroud)
如果您希望它永远运行(请参阅注释),请尝试:
n = 0
print(n)
while True:
n += 1
print(n)
Run Code Online (Sandbox Code Playgroud)
或使用for循环。
根据之前答案的评论,您想要这样的东西:
n = 0
while True:
if True: #Replace True with any other condition you like.
print(n)
n+=1
Run Code Online (Sandbox Code Playgroud)
编辑:
根据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
Run Code Online (Sandbox Code Playgroud)
注意:
对象序列化的方法有很多,上面的示例是最简单的方法之一,您可以使用专用的对象序列化模块,例如pickle等。
| 归档时间: |
|
| 查看次数: |
6282 次 |
| 最近记录: |