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

新手上路,请多包涵

鉴于 if 语句返回 true,我正在尝试增加整数的计数。然而,当这个程序运行时,它总是打印 0。我希望程序第一次运行时 n 增加到 1。到 2 第二次等等。

我知道函数、类和模块可以使用 global 命令,在它之外,但这不适用于 if 语句。

 n = 0
print(n)

if True:
    n += 1

原文由 Osuynonma 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 501
2 个回答

根据上一个答案的评论,你想要这样的东西吗:

 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 等等。

原文由 Ubdus Samad 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您希望它仅与 if 语句一起使用。我认为你需要放入一个函数并调用它自己,我们称之为递归。

 def increment():
    n=0
    if True:
        n+=1
        print(n)
        increment()
increment()

注意:在此解决方案中,它将无限运行。您也可以使用 while 循环或 for 循环。

原文由 Ali 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题