Search code examples
pythonpython-3.xif-statementglobal-variables

Conditionally increase integer count with an if statement in python


I'm trying to increase the count of an integer given that an if statement returns true. However, when this program is ran it always prints 0.I want n to increase to 1 the first time the program is ran. To 2 the second time and so on.

I know functions, classes and modules you can use the global command, to go outside it, but this doesn't work with an if statement.

n = 0
print(n)

if True:
    n += 1

Solution

  • Based on the comments of the previous answer, do you want something like this:

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

    EDIT:

    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.

    So the code for that goes as(Assuming 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
    

    NOTE: There are many methods of object serialization and the above example is one of the simplest, you can use dedicated object serialization modules like pickle and many others.