简体   繁体   中英

Python, If statement in function does not update a value inside the function

I'm trying to build a web scraping script which sends me an email when the price of a certain product changes. I use an "old_price" variable and a "current_price" variable. if the current price does not equal the old price, an email should be sent to me and the old price should become the current price. The problem lays inside the if statement. The old_price variable does not get updated, so the old price will never match the current price, thus sending me a email every time even when the price hasen't changed.

def checkPrice():
    old_price = 0.0
    current_price = soup.find("div", class_="fund-price").get_text()
    current_price = (current_price.lstrip("€"))
    current_price = float(current_price[0:4])
    print("old price is: ", old_price)
    print("current price is: ", current_price)
    if(current_price != old_price):
        old_price = current_price
        sendEmail()

while(True):
    checkPrice()
    time.sleep(3600)

You're setting old_price back to 0 every time checkPrice is called. The function doesn't "remember" values from previous invocations.

Instead, you could:

  1. make it a parameter that gets passed and returned, keep track of it in the calling function.
  2. turn it into a generator, which keeps track of its internal state.
  3. make a class and store the price as an instance variable.

Option 1 is the simplest:

def checkPrice(old_price):
    current_price = soup.find("div", class_="fund-price").get_text()
    current_price = (current_price.lstrip("€"))
    current_price = float(current_price[0:4])
    print("old price is: ", old_price)
    print("current price is: ", current_price)
    if(current_price != old_price):
        sendEmail()
    return current_price

price = 0.0    
while(True):
    price = checkPrice(price)
    time.sleep(3600)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM