Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 269
Osuynonma Avatar asked Apr 28 '26 06:04

Osuynonma


2 Answers

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.

like image 152
Ubdus Samad Avatar answered Apr 29 '26 19:04

Ubdus Samad


If you want it to work with if statement only. I think you need to put in a function and make to call itself which we would call it recursion.

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

Note: in this solution, it would run infinitely. Also you can use while loop or for loop as well.

like image 35
Ali Avatar answered Apr 29 '26 19:04

Ali