【问题标题】:Conditionally increase integer count with an if statement in python在python中使用if语句有条件地增加整数计数
【发布时间】:2018-03-02 04:30:35
【问题描述】:

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

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

n = 0
print(n)

if True:
    n += 1

【问题讨论】:

  • 请记住,Python 会按从上到下的顺序执行每一行代码。

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


【解决方案1】:

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

n = 0
while True:
    if True: #Replace True with any other condition you like.
        print(n)
        n+=1   

编辑:

根据 OP 在这个答案上的 cmets,他想要的是数据持续存在,或者更准确地说,变量 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 等等。

【讨论】:

  • 这会增加计数而无需我再次运行程序。我必须退出 IDE 才能终止它。我希望每次运行时都能将计数增加一。我不确定如何在这里使用 while 或 for 循环。任何额外的帮助将不胜感激。
  • 您不能以常规方式在程序的多次运行之间存储变量,您需要的是 Persisting Data,为此,您必须编写变量n 的值写入文件,然后每次运行它时,它都会从该文件(存储在本地驱动器上)中读取 n 的值,将其递增 1,然后将其再次写回文件。我将为此编辑代码。
【解决方案2】:

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

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

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

【讨论】:

  • 如果我需要它在每次运行程序时只运行一次,有没有办法在不使用 if 语句的情况下做到这一点?
  • 你的意思是如果你运行程序它会增加n?我没明白你的意思。
  • 如果我第一次点击程序运行,我希望 n 增加到 1,然后停止。当我第二次运行它时,我希望 n 增加到 2,等等。
  • 我想你可以按照这个链接:[stackoverflow.com/questions/44012748/…
【解决方案3】:

当您重新运行程序时,存储在内存中的所有数据都会被重置。您需要将变量保存在程序之外的某个位置,即磁盘上。

示例见How to increment variable every time script is run in Python?

ps。现在你可以简单地用 bool 做 +=:

a = 1
b = True
a += b  # a will be 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-10
    • 2021-10-04
    • 2022-11-05
    • 2021-06-19
    • 1970-01-01
    • 2013-09-07
    • 2013-01-16
    • 1970-01-01
    相关资源
    最近更新 更多