繁体   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