Conditionally increase integer count with an if statement in python - 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

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.

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.

When you rerun a program, all data stored in memory is reset. You need to save the variable somewhere outside of the program, on disk.
for an example see How to increment variable every time script is run in Python?
ps. Nowadays you can simply do += with a bool:
a = 1
b = True
a += b # a will be 2

Related

How do I run a conditional statement "only once" and every time it changes?

I might be asking a simple question. I have a python program that runs every minute. But I would like a block of code to only run once the condition changes? My code looks like this:
# def shortIndicator():
a = int(indicate_5min.value5)
b = int(indicate_10min.value10)
c = int(indicate_15min.value15)
if a + b + c == 3:
print("Trade posible!")
else:
print("Trade NOT posible!")
# This lets the processor work more than it should.
"""run_once = 0 # This lets the processor work more than it should.
while 1:
if run_once == 0:
shortIndicator()
run_once = 1"""
I've run it without using a function. But then I get an output every minute. I've tried to run it as a function, when I enable the commented code it sort of runs, but also the processing usage is more. If there perhaps a smarter way of doing this?
It's really not clear what you mean, but if you only want to print a notification when the result changes, add another variable to rembember the previous result.
def shortIndicator():
return indicate_5min.value5 and indicate_10min.value10 and indicate_15min.value15
previous = None
while True:
indicator = shortIndicator()
if previous is None or indicator != previous:
if indicator:
print("Trade possible!")
else:
print("Trade NOT possible!")
previous = indicator
# take a break so as not to query too often
time.sleep(60)
Initializing provious to None creates a third state which is only true the first time the while loop executes; by definition, the result cannot be identical to the previous result because there isn't really a previous result the first time.
Perhaps also notice the boolean shorthand inside the function, which is simpler and more idiomatic than converting each value to an int and checking their sum.
I'm guessing the time.sleep is what you were looking for to reduce the load of running this code repeatedly, though that part of the question remains really unclear.
Finally, check the spelling of possible.
If I understand it correctly, you can save previous output to a file, then read it at the beginning of program and print output only if previous output was different.

How do i increase the value of an variable in a command line?

a = 1
for i in range(5):
browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]/div/div/div[1]/div[3]/button").click()
sleep(1)
I want to increase the 1 in div[1] by 1+ every loop, but how can i do that?
i thought i need to add a value, do "+a+" and last of all a "a = a + 1" to increase the value every time, but it didnt worked.
a = 1
for i in range(5):
browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]/div/div/div["+a+"]/div[3]/button").click()
a = a + 1
sleep(1)
for i in range(1,6):
browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]/div/div/div["+str(i)+"]/div[3]/button").click()
sleep(1)
you don't need 2 variables, just one variable i in the loop, convert it to string with str() and add it to where you need it, pretty simple. the value of i increases for every iteration of the loop going from 1 to 5 doing exactly what you need.
alternatively to Elyes' answer, you can use the 'global' keyword at the top of your function then a should increment 'correctly'.
You don't really need two variables for this unless you are going to use the second variable for something. However, look at the following code and it will show you that both i and a will give you the same result:
from time import sleep
a = 1
for i in range(1, 6):
path = "/html/body/div[6]/div/div/div[2]/div/div/div[{idx}]/div[3]/button".format(idx=i)
print(path, 'using i')
path = "/html/body/div[6]/div/div/div[2]/div/div/div[{idx}]/div[3]/button".format(idx=a)
a += 1
print(path, 'using a')
sleep(1)
Result:
/html/body/div[6]/div/div/div[2]/div/div/div[1]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[1]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[2]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[2]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[3]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[3]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[4]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[4]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[5]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[5]/div[3]/button using a
You can read up on range here

while loop does not pass to another while loop

i have two functions with while loop, the results from the first loop is used in the second one as an until condition, but when calling the two functions in the main it execute only the first one and it doesn't even enter the second function it just give me the results of the first loop.
in the first function self.user_association() there is a linear optimization using PULP i though it is the one causing the problem but it was not because when calling the loop function block_estimated_access_link() in the second one it works just fine but my program does not work that way because as i said i use the results from the first loop in the second one. Here is the code, can someone tell me what am i doing wrong or what is the problem exactly?
def block_Estimation_ACCESS_LINK(self):
while (self.iteration < self.Iter_max):
self.User_association()
self.estimated_access_power()
self.calcul_alpha()
self.calcul_rate_am()
self.User_association()
self.iteration += 1
def block_bg_power_allocation(self):
EPS = 0.0000000000001
RamTot = 0
while (self.iteration < self.Iter_maxB):
self.calcul_power_backhaul()
print('backhaul Pok=', self.p_ok)
self.calcul_delta()
self.calcul_rok()
for i in self.station:
for j in self.users:
self.Ram = numpy.delete(self.Ram, self.Ram[0])
RamTot = sum(self.Ram)
if EPS <= (self.Rok[i] - sum(self.Ram[i])):
self.iteration += 1
def main(self):
self.block_Estimation_ACCESS_LINK()
self.block_bg_power_allocation()
In the first function you're doing this:
self.iteration += 1
And then, in the second function your stop condition is:
while (self.iteration < self.Iter_maxB):
So the first function would increment self.iteration to self.Iter_max. Now, if self.Iter_maxB is the same value as self.Iter_max, your second functions loop will never execute. I suspect that's what's happening here. Check those two varaibles.
Fix would be something like this if you want to execute both those loops the same number of time:
def main(self):
self.block_Estimation_ACCESS_LINK()
self.iteration = 0
self.block_bg_power_allocation()

How do I prevent python from freezing to work on a large number equation?

Because it takes too much time to calculate for A, I'll want the calculation to stop and have the program continue on to calculate for B. It would also be helpful to know what error this is called.
A = 999999999999999999**999999999999999999
B = 9**9
The program still freezes when using threading.Timer()
import threading
import time
a = 1
def zzz():
global a
print('restarting')
a = 0
threading.Timer(1.0,zzz).start()
a = 1
threading.Timer(1.0, zzz).start()
while 1:
while a == 1:
h = 999999999999999**999999999999999
I believe the problem has been solved: adding ".0" at the end of one number will allow python to recognize that 99999999999999.0**99999999999999 is too large of a result and will output an error that can be ignored with try/except

Why does this code make my Python interpreter hang?

I had an identical problem with my other laptop, which led me to get this new one (new in the NBC after Friends sense) -- the interpreter would hang on some kind of nested iteration, and even freeze up and/or go berserk if left to its own devices. In this case, I CTRL+C'd after about five seconds. The interpreter said it stopped at some line in the while loop, different each time, indicating that it was working but at a slooooooooooow pace. Some test print statements seemed to show some problem with the iteration controls (the counter and such).
Is it a CPU problem, or what?
from __future__ import print_function
import sys
# script is a useless dummy variable, setting captures the setting (enc or dec), steps captures the number of lines.
script, setting, steps = sys.argv
# Input handling bloc.
if setting not in ('enc', 'dec'):
sys.exit("First command line thing must either be 'enc' or 'dec'.")
try:
steps = int(steps)
except:
sys.exit("Second command line thing must be convertable to an integer.")
# Input string here.
string_to_convert = raw_input().replace(' ', '').upper()
if setting == 'enc':
conversion_string = ''
counter = 0
while len(conversion_string) < len(string_to_convert):
for char in string_to_convert:
if counter == steps:
conversion_string += char
counter = 0
counter += 1
steps -= 1
print(conversion_string)
Depending on the starting value of steps its possible for counter and steps to never be equal, which means conversion_string is never altered, so it is always shorter than string_to_convert and the loop never ends.
A naive example is, let steps=-1, since counter starts at 0 and increments, and steps always decrements, they will never be equal.
Actually, on further inspection, if steps is less than len(string_to_convert) this will always end in an infinite loop.
Consider:
steps=2
string_to_convert="Python"
The first iteration of the for loop will iterate counter to 2 and fetch the "t"; now steps = 1, conversion_string="t"
Next for loop will iterate counter to 1, fetch the "y"; now steps = 0, conversion_string="ty"
for loop iterates counter to 0, fetch the "P"; now steps = -1, conversion_string="tyP"
Now, steps = -1, counter can never equal it, for loop ends without changing conversion_string.
Step 4 repeats while decreasing steps without any ability to quit the while loop.
Thus, why it sometimes works and sometimes doesn't.

Categories