I am currently scraping a web page and a certain variable minute is changed every few seconds. This minute is located inside a def which runs forever. How can I make it so if, for example, minute == 80, the if statement only runs once?
Here is how the code looks like:
def login(): # necesarry for this
// stuff
return r
def run(r): //stuff minute_soup = soup.find_all("span", {"class":"clock-period"}) minute = minute_soup[0].text if minute == 80: print(minute) time.sleep(10)
r = login()
while True: run(r) Currently, each time minute is equal to 80, it does the same thing over and over again, every 10 seconds until minute is not equal to 80. Is there any way for it to do it once when minute is equal to 80?
4 Answers
You could use the parameter to hold a flag:
def run(r): //stuff minute_soup = soup.find_all("span", {"class":"clock-period"}) minute = minute_soup[0].text if minute == 80 and r.flag: r.flag = False print(minute) if minute != 80: r.flag = True time.sleep(10)
r = login()
r.flag = True
while True: run(r) As I understood from your question you can use a flag and when first time minutes become 80 set it true then if will never execute again:
def login(): # necesarry for this
// stuff
return r
def run(r): //stuff minute_soup = soup.find_all("span", {"class":"clock-period"}) minute = minute_soup[0].text flag = False if (minute == 80 and !flag): flag = True print(minute) time.sleep(10)
r = login()
while True: run(r) 1 It would be something like this:
flag = true
def run(r): if r == 80: if flag: flag = false //More stuff else: flag = trueI suggest you look into eventhandling, because infinite-looping can usually be resolved by using events which results in cleaner code
1minuteRunOnce = False
def run(r): //stuff minute_soup = soup.find_all("span", {"class":"clock-period"}) minute = minute_soup[0].text if (minute == 80 and not(minuteRunOnce)): print(minute) minuteRunOnce = True time.sleep(10)
r = login()
while True: run(r) 0