嘿,我正在嘗試制作一個非常簡單的應用程式來檢查實際的 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 價格,下一個值與第一個值不同,然后檢查它是更低還是更高并列印特定值
uj5u.com熱心網友回復:
您的問題是您沒有設定回圈中的last_price任何位置。for您需要last_price在回圈結束之前和獲得下一個當前價格之前將其更新為當前價格,以便您可以比較兩者。如果價格沒有變化,則不會列印任何內容。
請注意,您的嵌套if陳述句是多余的。<and>運算子如果False兩個值相等則回傳,因此如果回傳True則暗示兩個值不相等,因此無需檢查。
我建議在您的價格上漲/下跌宣告中添加時間戳。我還建議添加一個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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/457693.html
