while 循环和 if 语句的问题

Issue with while loop and if statement

嘿,我正在尝试制作一个非常简单的应用程序来检查实际的 btc 价格并检查 last_price 是否低于或高于实际价格,但我无法弄清楚为什么应用程序卡在这个声明上并且只继续发送垃圾邮件一:

    elif price > last_price:
  if last_price != price:
    print(Fore.GREEN + "Bitcoin price has increased: $", functions.getbtcprice())

这是代码: main.py

from btcapi import *
from colorama import Fore

def main(): 
  last_price = -1
  while True:
    price = functions.getbtcprice() 
    if last_price == -1:
      print("Bitcoin price: $",price)
      last_price = price
    elif price > last_price:
      if last_price != price:
        print(Fore.GREEN + "Bitcoin price has increased: $", functions.getbtcprice())
    elif price < last_price:
      if last_price != price:
        print(Fore.RED + "Bitcoin price has decreased: $", functions.getbtcprice())
     
if __name__ == "__main__":
    main()

btcapi.py

import requests
import json

class functions:  
    def getbtcprice():   
        response = requests.get("https://api.coinbase.com/v2/prices/spot?currency=USD").text
        response_info = json.loads(response)
        return float(response_info["data"]["amount"])

这就是问题所在:

https://imgur.com/a/WzDeByF

我想做的是第一次打印实际的 btc 价格和下一个与第一个不同的值检查它是更低还是更高并打印特定值

您的问题是您没有在 for 循环中的任何位置设置 last_price。您需要在循环结束之前以及获得下一个当前价格之前将 last_price 更新为当前价格,以便您可以比较两者。如果价格没有变化,则不会打印任何内容。

请注意,您的嵌套 if 语句是多余的。 <> 运算符 return False 如果两个值相等,那么如果它们 return True 则暗示这两个值相等,因此不需要检查。

我建议在您的价格 increase/decrease 声明中添加时间戳。我还建议添加一个 time.sleep(),这样您就不会每分钟点击 API 数千次。

from btcapi import *
from colorama import Fore


def main(): 
  # Initialize current and previous prices
  current_price = functions.getbtcprice()
  last_price = current_price
  print("Bitcoin price: $", current_price)
  while True:
    if current_price > last_price:
      print(Fore.GREEN + "Bitcoin price has increased: $", current_price)
    elif current_price < last_price:
      print(Fore.RED + "Bitcoin price has decreased: $", current_price)
    # Set last_price to current_price, then update current_price
    last_price = current_price
    current_price = functions.getbtcprice()


if __name__ == "__main__":
    main()