How to Make Python Code to Execute Only Once

How do I make Python code to execute only once?

you could create a file once set up is complete for example an empty .txt file and then check if it exists when program runs and if not runs setup

to check weather a file exists you can use os.pathlike so

import os.path
if not os.path.exists(file_path):
#run start up script
file = open (same_name_as_file_path, "w") #creates our file to say startup is complete you could write to this if you wanted as well
file.close

Is there a way to execute a statement only once in python?

Sure, there are multiple ways.

You could have a mutable function, then your code would look like this:

def function(given_items=[]):
print("What do you want to do?")
userInput = input("1. Talk to the blacksmith \n2. Leave\n")
if userInput == "1":
# if the user hasnt already received the sword:
if not "sword" in given_items:
print("the BLACKSMITH gifts you a sword")
given_items.append("sword")
else:
print("Hi, how can I help?")
function()

function()

Word of caution regarding mutable arguments: https://florimond.dev/en/posts/2018/08/python-mutable-defaults-are-the-source-of-all-evil/

Or you could have a global flag or array, something like:

GIVEN_ITEMS = []
# SWORD_GIVEN = FALSE # You could also use a boolean instead of a list, the advantage with a list is that it allows you to keep track of all such items instead of having a boolean flag for every single item.

def function():
print("What do you want to do?")
userInput = input("1. Talk to the blacksmith \n2. Leave\n")
if userInput == "1":
# if the user hasnt already received the sword:
if not "sword" in GIVEN_ITEMS:
print("the BLACKSMITH gifts you a sword")
GIVEN_ITEMS.append("sword")
else:
print("Hi, how can I help?")
function()

function()

How to make a few lines of function execute only once in python? preferably using lambda?

You can use a decorator for this.

Using class based decorator:

class callonce(object):

def __init__(self, f):
self.f = f
self.called = False

def __call__(self, *args, **kwargs):
if not self.called:
self.called = True
return self.f(*args, **kwargs)
print 'Function already called once.'

Using function attribute:

from functools import wraps

def callonce(f):

@wraps(f)
def wrapper(*args, **kwargs):
if not wrapper.called:
wrapper.called = True
return f(*args, **kwargs)
print 'Function already called once.'
wrapper.called = False
return wrapper

Now add the decorator above your function:

@callonce
def func():
print "Creating Table"

Demo:

>>> func()
Creating Table
>>> func()
Function already called once.
>>> func()
Function already called once.

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

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.



Related Topics



Leave a reply



Submit