I have a simple if statement in my code
if len(bootstrap_node_list_recieved_no_dups) >= min_node_to_complete_boot_strap:
print "recieved required nodes"
Basically I want to know if have enough nodes, I only want this to occur once, as the code will still carry on and be run repeatedly so currently this if statement is run every time as I would expect.
Is there a way to code it so the if statement is run, but after it completes once it is never run again?
The >= is required as the input is not a constant.
I hope this is clear, as it's a bit hard to describe.
Update,
i have tried to implement the suggestions but am getting the error
UnboundLocalError: local variable 'flag' referenced before assignment
full code below:
flag = False
def number_of_duplicates_in_list():
number_recieved = len(bootstrap_node_list_recieved)
bootstrap_node_list_recieved_before = len(bootstrap_node_list_recieved_no_dups)
" this method works in O(n^2) time and is thus very slow on large lists"
for i in bootstrap_node_list_recieved:
if i not in bootstrap_node_list_recieved_no_dups:
bootstrap_node_list_recieved_no_dups.append(i)
assert len(bootstrap_node_list_recieved_no_dups) >= bootstrap_node_list_recieved_before
if len(bootstrap_node_list_recieved_no_dups) >= min_node_to_complete_boot_strap and flag is False:
print "recieved required nodes"
flag = True
You could have some flagging variable that is changed when the if statement is first triggered. The below code is a minimal example which will only print the 'Triggered' statement once, even though all numbers above 3 would trigger the statement if the flag was not also being checked.
flag = False
for x in xrange(10):
if x > 3 and flag is False:
print 'Triggered'
flag = True
# Do something else
If you want to do this inside a function, you need to move the flag initialisation into the function as well. Note that re-running the function will reset the flag:
def test_func():
flag = False
for x in xrange(10):
if x > 3 and flag is False:
print 'Triggered'
flag = True
# Do something else
test_func()
To be able to run the function multiple times but only trigger the if statement and change the flag once, you need to link the flag to the function calls. A simple method of doing this is to pass and return the flag on each call:
flag = False
def test_func(flag):
for x in xrange(10):
if x > 3 and flag is False:
print 'Triggered'
flag = True
# Do something else
return flag
flag = test_func(flag)
flag = test_func(flag)
Here, the flag is define outside of the function and passed to each function when called. If not triggered, it passes through without change. If triggered, it is changed and its state passed back outside the function.
Other approaches could be defining a global variable or building a class with the flag as an object variable and accessing it via self.
Define flag to be global within number_of_duplicates_in_list. Otherwise, you can only read it.
Related
I've created a subprogram called DEVICE_ON in which I've defined some of these statements
if j == 2:
print('shutdown')
# Run command.
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(shutdown)
var_colonna_2=data_array[i][j]
return var_colonna_2
var_colonna_2 is a string value (could be "X" or "V") and in this subprogram I have 8 return value (one for each var_colonna)
Now in the main programm I'm calling another subprogramm defined as:
CHECK_TEST(var_colonna_1, var_colonna_2, var_colonna_3, var_colonna_4,
var_colonna_5, var_colonna_6, var_colonna_7, var_colonna_8)
this CHECK_TEST of course is executed after the DEVICE_ON.
So basically In the main programm I have something like:
DEVICE_ON(ssh,data_array, i, j)
CHECK_TEST(var_colonna_1,var_colonna_2, var_colonna_3, var_colonna_4,
var_colonna_5, var_colonna_6, var_colonna_7, var_colonna_8)
I was expecting that, since in DEVICE_ON, I've defined the return value for var_colonna_x (x=1 to 8), automatically the value of each var_colonna was updated and received from CHECK_TEST for internal computation,but right now it always sees 0.
I've also tried with the debug.It seems that the values are passed, but I still don't get why they are not seen in the next subprogram.
I've understand where my mistake was.
Basically the retur function is ok but in the main I was missing something like:
var_colonna_1=CHECK_TEST(var_colonna_1, var_colonna_2, var_colonna_3, var_colonna_4, var_colonna_5, var_colonna_6, var_colonna_7, var_colonna_8)
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.
I have a question about recalling my function within a loop.
Below is my code:
List_new = myfunction()
for items in List_new:
if(my condition is TRUE):
Execute some commands
if(my condition is FALSE):
recall myfunction()
My problem is that I am loading "List_new" using myfunction(). How can I change "List_new" iteratively when my condition is False. I want to reload the function especially when the condition is FALSE. This means I keep calling the function until it is false and then execute the final output from myfunction().
Thank you in advance for your help.
I am going to assume the list generated by myfunction() is a constant size.
You can use a while loop:
List_new = myfunction()
index=0
while index < len(List_new):
items = List_new[index]
if(my condition is TRUE):
#Execute some commands
i+=1
if(my condition is FALSE):
List_new = myfunction()
Keep in mind that this solution will have an infinite loop if myfunction() continuously generates false values. If you can guarantee that all values will eventually be True then it should always terminate.
Does or condition work in a while loop in python? I can't seem to make it work. This is the sample of how my code works.
newslot = 3
moved = False
while newslot > 0 or moved != True:
enabled = query something on the database where slot = newslot
if enabled:
print 'do something here'
moved = True
else:
newslot-=1
print 'slot disabled'
So when the newslot gets to value of zero it still proceeds to go inside the while loop.
I seem to be missing something here.
or is working as should be expected. A while loop will continue until its condition is false. If its condition is two separate conditions connected with an or, it will only be false when the two conditions are both false.
Your loop will continue repeating until moved is false and newslot is <= 0. I'm guessing you actually want to use and in this case, as you want the loop to stop once either condition is met.
As I know, "continue" will jump back to the top of the loop. But in my case it's not jumping back, continue don't like me :(
for cases in files:
if ('python' in cases.split()):
execute_python_scripts(cases.split())
elif run_test_case(cases.split()):
continue
else:
logger("I am here")
break
In my case run_test_case() gives 1, 2, 3, 4 etc... But it always performs first(1) and jump to the else part. So I am getting the "I am here" message. It should not work like this. As I am using "continue", it should jump to the for loop.
Following is the run_test_case():
def run_test_case(job):
for x in job:
num_of_cases = num_of_cases - 1
test_type = x.split('/')
logger(log_file,"Currently "+ x +"hai!!")
if test_type[0] == 'volume':
backdoor = test_type[1].split("_")
if backdoor[0] == 'backdoor':
return get_all_nas_logs()
else:
if perform_volume_operations(x,num_of_cases) == False:
return False
else:
logger(log_file,"wrong ha!!")
Why is it always going to the else part, without jumping back to the for loop? Thanks in advance.
Here elif run_test_case(cases.split()): you are calling the run_test_case method, that will run your code to evaluate the result for the elif condition.
It only enters the block delimited by elif (in your case, continue), if the result of that method evaluates to True, otherwise it will jump to the else clause.
The problem is probably in your run_test_case code, that is never returning True, and so you'll never get the behavior that you're expecting.
It's hard to say without knowing exactly what you want to accomplish, but I'd say that you're missing a return True in the end of that code, meaning, if everything executes correctly right until the end, you want it to return True... but I'm only guessing here, you need to think about what that method is supposed to do.
In python an if or elif clause is evaluated for not only the True and False constants, but more generally for True-like and False-like values. None, for instance, is a false-like value, a non-empty string is a true-like value, etc.
Check this from the documentation on values that are considered true or false:
http://docs.python.org/library/stdtypes.html