簡體   English   中英

Python,function 中的 If 語句不更新 function 中的值

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

我正在嘗試構建一個 web 抓取腳本,當某個產品的價格發生變化時,它會向我發送 email。 我使用“old_price”變量和“current_price”變量。 如果當前價格不等於舊價格,則應向我發送 email,舊價格應成為當前價格。 問題在於 if 語句。 old_price 變量不會更新,因此舊價格永遠不會匹配當前價格,因此即使價格沒有變化,每次都會向我發送 email。

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)

每次調用checkPrice時,您都將old_price設置回 0。 function 不會“記住”先前調用的值。

相反,您可以:

  1. 使其成為傳遞和返回的參數,在調用 function 中跟蹤它。
  2. 把它變成一個生成器,它跟蹤它的內部 state。
  3. 制作 class 並將價格存儲為實例變量。

選項 1 是最簡單的:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM