python - 在 python 中使用 if 语句有条件地增加整数计数

标签 python python-3.x if-statement global-variables

假设 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/

相关文章:

python - 在 python 中对列表使用 if 语句?

excel - 在Excel 2017中嵌套6个IF语句并获得#NAME?错误

C++, 'if' 表达式中的变量声明

python - Django 说 MySQL 不允许唯一的 CharFields 有一个 max_length > 255,但它允许

python-3.x - 当最大像素值小于65535时,如何规范化uint16图像并将其转换为uint8?

python - 如何在(python)中获取带有表情符号的内容子串

python - 使用 BeautifulSoup 提取 HTML 注释之间的文本

python - 因此,我正在制作一个程序,可以多次向用户重复问候语,但是当他们想要继续时,它不会显示该代码

python - Django 表单集困难

python - 向量化 for 循环 Python