Home > other >  Issue with while loop and if statement
Issue with while loop and if statement

Time:04-07

Hey Im trying to make pretty simple app that check actual btc price and check if last_price is lower or higher then actual, but I cant figure out why is app stuck on this statement and keep spamming only this one:

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

Here is code: 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()

and 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"])

Thats the problem:

https://imgur.com/a/WzDeByF

What Im trying to do is print first time actual btc price and the next one value different then the first one check if its lower or higher and print specififc values

CodePudding user response:

Your issue is that you are not setting the last_price anywhere in your for loop. You need to update the last_price to the current price before your loop ends, and before you get the next current price, so that you can compare the two. Nothing will be printed if the price hasn't changed.

Note that your nested if statements were redundant. The < and > operators return False if the two values are equal, so if they return True then it is implied that the two values are not equal, and is therefore unnecessary to check.

I suggest adding timestamps to your price increase/decrease statements. I also suggest adding a time.sleep() so that you're not hitting the API thousands of times per minute.

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()
  • Related