Refresh multiple print lines within terminal - python

Super simple not complex and don't need it to be. Just wanted to add the current prices of crypto and my equity of these prices as well as a total to display on screen. I want these values to refresh in place so they don't create new lines every time it refreshes.
Here is what I have:
import requests
import math
from datetime import datetime
URL = "https://min-api.cryptocompare.com/data/price?fsym={}&tsyms={}"
def get_price(coin, currency):
try:
response = requests.get(URL.format(coin, currency)).json()
return response
except:
return False
while True:
date_time = datetime.now()
date_time = date_time.strftime("%m/%d/%Y %H:%M:%S")
currentPrice = get_price("ETH", "USD")
totalPrice = currentPrice["USD"]*2
currentPrice0 = get_price("DOGE", "USD")
totalPrice0 = currentPrice0["USD"]*100
currentPrice1 = get_price("ADA", "USD")
totalPrice1 = currentPrice1["USD"]*20
currentPrice2 = get_price("SOL", "USD")
totalPrice2 = currentPrice2["USD"]*4
currentPrice3 = (totalPrice + totalPrice0 + totalPrice1 + totalPrice2)
print("ETH | PRICE: $", currentPrice["USD"], " EQUITY: $", totalPrice)
print("DOGE | PRICE: $", currentPrice0["USD"], " EQUITY: $", totalPrice0)
print("ADA | PRICE: $", currentPrice1["USD"], " EQUITY: $", totalPrice1)
print("SOL | PRICE: $", currentPrice2["USD"], " EQUITY: $", totalPrice2)
print(" ")
print("TOTAL: ", currentPrice3)

Related

Lab: calculate discounts

I'm doing an exercise and so far so good as the code (after some help from other threads) now works almost fine, but...can't get the right results as a math point of view.
Here it's the code:
#getting base prices from user
item1 = float(input('Enter the price of the first item: '))
item2 = float(input('Enter the price of the second item: '))
clubc = raw_input('Does customer have a club card? (Y/N): ')
tax = float(input('Enter tax rate, e.g. 5.5 for 5.5% tax: '))
basep = (item1 + item2)
print('Base price = ', basep)
#setting variables for calculation
addtax = (1 + (tax / 100))
#conditions for output
if item1 >= item2 and clubc == 'N':
priceafterd = float(item1 + (item2 / 2))
print('Price after discounts = ', priceafterd)
totalprice = (priceafterd * addtax)
print('Total price = ', totalprice)
elif item2 >= item1 and clubc == 'N':
priceafterd = float(item2 + (item1 / 2))
print('Price after discounts = ', priceafterd)
totalprice = (priceafterd * addtax)
print('Total price = ', totalprice)
if item1 >= item2 and clubc == 'Y':
priceafterd = float((item1 + (item2 / 2)) * 0.9)
print('Price after discounts = ', priceafterd)
totalprice = (priceafterd * var3)
print('Total price = ' + totalprice)
else:
priceafterd = float((item2 + (item1 / 2)) * 0.9)
print('Price after discounts = ', priceafterd)
totalprice = (priceafterd * var3)
print('Total price = ' + totalprice)
The exercise requires to write a program that computes how much a customer has to pay after purchasing two items, depending on a promo, club card and taxes.
The problem is with the results. As an example of inputs:
Enter price of the first item: 10
Enter price of the second item: 20
Does customer have a club card? (Y/N): y
Enter tax rate, e.g. 5.5 for 5.5% tax: 8.25
Base price = 30.00
Price after discounts = 22.50
Total price = 24.36
Instead, I got:
line 33, in <module>
print('Total price = ' + totalprice)
TypeError: cannot concatenate 'str' and 'float' objects
What's wrong with the syntax? Thanks a lot!
The problem
In the second conditional you wrote print('Total price = ' + totalprice) line instead of the print('Total price = ', totalprice), and the problem is in that:
totalprice has float type, meanwhile 'Total price = ' is the str and what you are trying to do is almost like str() + float(), and because python doesn't know how to concatenate string and float number it raises an exception.
How to solve
1) Use the same print('Total price = ', totalprice) line everywhere
Why does it work and print('Total price = ' + totalprice) does not?
Because print automatically converts everything to string representation, you can imagine print('Total price = ', totalprice) expression like that:
print(str('Total price = ') + " " + str(totalprice))
2) Convert float to str and concatenate strs
print('Total price = ' + str(totalprice))
str(totalprice) converts totalprice from float to the str and python knows how to concatenate strings together.
3) Formatting
"Total price = {}".format(3.14)" is equivalent to the "Total price = 3.14" string,
so print("Total price = {}".format(totalprice)) also will work
in python 3 we also have f-stings:
f"Total price = {3.14}" == "Total price = 3.14"
print(f"Total price = {totalprice}")

Bitcoin sell or buy Monitor with Colours( in cmd/win10)

This is my goal ;)
I try to write a Python Script which prints the Bitcoin Price and set the colours green or red (higher price -->Green/ falling price --> Red) .
now, its prints all in red (Fore.RED)But how can i write the code?
if Pricefloat higher then xxx print green else: red
many thanks for help... :)
code:
import requests, json
from time import sleep
from colorama import init, Fore, Back, Style
def getBitcoinPrice():
URL = 'https://www.bitstamp.net/api/ticker/'
try:
r = requests.get(URL)
priceFloat = float(json.loads(r.text)['last'])
return priceFloat
except requests.ConnectionError:
print ("Error querying Bitstamp API")
while True:
init(convert=True)
print (Fore.RED + "Bitstamp last price: $" + str(getBitcoinPrice()) + "/BTC")
In your while loop, I think what you want is:
price = getBitcoinPrice()
if price > 8000: # Or whatever price
print (Fore.RED + "Bitstamp last price: $" + str(price) + "/BTC")
else:
print (Fore.GREEN + "Bitstamp last price: $" + str(price) + "/BTC")

How to find the closest number in CSV file that is the closest to a user input?

I'm still new to Python. I want to make a Car loan calculator that only runs in command prompt. The Calculator needs to take input from the users.
I managed to get the input of the users and print the list of prices in the CSV file. I need to find the closest price in the CSV file that is closest to my variable vehiclecost. Is there any code I can use to do that?
Code:
carlist = open("carlist.csv")
data = carlist.readline()
print("Vehicle cost:")
vehiclecost = float(input().strip("! .? % $"))
print("Annual interest rate:")
AnnualInterestRate = float(input().strip("! .? % $"))
print("Loan duration:")
loandur = int(input().strip("! .? % $"))
while loandur > 10:
print("Try again your loan duration is too long!")
loandur = float(input().strip("! .? % $"))
loanmonth = (loandur * 12)
carwithtax = (vehiclecost * 0.12 + vehiclecost)
InterestRate = AnnualInterestRate / (100 * 12)
monthlypayment = carwithtax * (InterestRate *
((InterestRate + 1)**loanmonth)) / ((InterestRate + 1)**loanmonth - 1)
print("Your loan amount would be: " + str(carwithtax))
print("Your monthly payment would be: {:.2f}".format(monthlypayment))
for x in range(1, loandur + 1):
for y in range(12):
monthlyinterest = (carwithtax * InterestRate)
principal = (monthlypayment - monthlyinterest)
carwithtax = float(carwithtax - principal)
print("Years:", x)
print("Bal remaining: {:.2f}".format(carwithtax))
month = x * 12
print("Total payemtns, {:.2f}".format(month * monthlypayment))
print("Car Recomendation")
for data in carlist:
price = data.split(",")
if int(price[0]) < vehiclecost:
lower = data.split(",")
print(lower)
My input file: Carlist.csv
Snippet
To find the closest value vehicle from the data set:
# get the price list from the csv
price_list = [row[0] for row in car_list]
# get the closest value vehicle
closest_value_vehicle = min(price_list, key=lambda x:abs(int(x)-vehicle_cost))
Full Code
I cleaned up the code a little and added commenting.
Tested with the supplied dataset.
import csv
with open('carlist.csv', 'r') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
# skip header
next(reader, None)
# assign car list
car_list = list(reader)
while True:
try:
# vehicle cost
vehicle_cost = float(input("Please enter the vehicle cost:").strip("! .? % $"))
except ValueError:
print("Invalid input. Vehicle cost must be numeric.")
continue
else:
break
while True:
try:
# annual interest rate
annual_interest_rate = float(input("Please enter the annual interest rate:").strip("! .? % $"))
except ValueError:
print("Invalid input. Annual interest rate must be numeric.")
continue
else:
break
while True:
try:
# loan duration
loan_duration = int(input("Please enter the loan duration:").strip("! .? % $"))
except ValueError:
print("Invalid input. Loan duration must be numeric.")
continue
if loan_duration > 10:
print("Invalid input. Loan duration must be less than 10.")
continue
else:
break
# total loan months
loan_total_months = loan_duration * 12
# vehicle tax
vehicle_tax = vehicle_cost * 0.12 + vehicle_cost
# interest rate
interest_rate = annual_interest_rate / ( 100 * 12 )
# monthly repayment
monthly_repayment = vehicle_tax * ( interest_rate * ( ( interest_rate + 1 ) ** loan_total_months ) ) / ( ( interest_rate + 1 ) ** loan_total_months - 1 )
print("Your loan amount would be: $%s" % str('{:,}'.format(vehicle_tax)) )
print("Your monthly payment would be: {:.2f}".format(monthly_repayment) )
# repayments
for x in range(1, loan_duration + 1):
for y in range(12):
monthly_interest = (vehicle_tax * interest_rate)
principal = (monthly_repayment - monthly_interest)
vehicle_tax = float(vehicle_tax - principal)
print("Years:", x)
print("Balance remaining: ${:.2f}".format(vehicle_tax))
month = x * 12
print("Total payments: ${:.2f}".format(month*monthly_repayment))
# vehicles in price range
vehicles_in_price_range = []
# get the price list from the csv
price_list = [row[0] for row in car_list]
# get the closest value vehicle
closest_value_vehicle = min(price_list, key=lambda x:abs(int(x)-vehicle_cost))
print(closest_value_vehicle)
for row in car_list:
# price
price = row[0]
# check if price in range
if int(price) == int(closest_value_vehicle):
vehicles_in_price_range.append(row)
print("Vehicle Recomendations:")
# print list of vehicles in price range
for vehicle in vehicles_in_price_range:
print('%s %s %s (VIN: %s) (Millage:%s) (Location: %s, %s) - $%s' %
( vehicle[1],
vehicle[6],
vehicle[7],
vehicle[5],
vehicle[2],
vehicle[3],
vehicle[4],
str('{:,}'.format(int(vehicle[0]))) ) )

Want program to send ONE email at the end of program with all the data

So I have a code I made that makes it so it checks the weather for you etc.
I have it also so it sends you an email (if you want it to) with the data for your weather search.
BUT, it only sends the last search you did, not all the searches.
I have no idea how I would go about getting the code to gather all the data within the loop and THEN send the email with all answers and searches. The code here is just the normal code I have, not with a try for it to gather all data and then send it, I really dont know how I would make it do that :p
# - Good Morning Program -
#Import
import datetime
import requests
import sys
import smtplib
import ad_pw
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#Input
name_of_user = input("What is your name?: ")
#Email
sender_email = ad_pw.email_address
password = ad_pw.email_password
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(sender_email, password)
#Loop
while True:
#Input
city = input('City Name: ')
# API
api_address='http://api.openweathermap.org/data/2.5/weather?appid=0c42f7f6b53b244c78a418f4f181282a&q='
url = api_address + city
json_data = requests.get(url).json()
# Variables
format_add = json_data['main']['temp']
day_of_month = str(datetime.date.today().strftime("%d "))
month = datetime.date.today().strftime("%b ")
year = str(datetime.date.today().strftime("%Y "))
time = str(datetime.datetime.now().strftime("%H:%M:%S"))
degrees = format_add - 273.15
humidity = json_data['main']['humidity']
latitude = json_data['coord']['lon']
longitude = json_data['coord']['lat']
#Program
if degrees < 20 and time > str(12.00):
print("\nGood afternoon " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a mild " + "{:.1f}".format(degrees) +
"°C, you might need a jacket.")
elif degrees < 20 and time < str(12.00):
print("\nGood morning " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a mild " + "{:.1f}".format(degrees) +
"°C, you might need a jacket.")
elif degrees >= 20 and time > str(12.00):
print("\nGood afternoon " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a warm " + "{:.1f}".format(degrees) +
"°C, don't forget to drink water.")
elif degrees >= 20 and time < str(12.00):
print("\nGood morning " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a warm " + "{:.1f}".format(degrees) +
"°C, don't forget to drink water.")
restart = input('Would you like to check another city (y/n)?: ')
if restart == 'y':
continue
else:
# HTML
html_message = """\
<html>
<head></head>
<body>
<p>Hi, """ + str(name_of_user) + """<br>
Here is the data from your weather search:<br>
<br>
City: """ + str(city) + """<br>
Temperature: """ + "{:.1f}".format(degrees) + """°C<br>
Humidity: """ + str(humidity) + """%<b>
</p>
</body>
</html>
"""
# Email
msg = MIMEMultipart('alternative')
msg = MIMEText(html_message, "html")
receive_email = input("Do you want to receive a copy from you search (y/n)?: ")
if receive_email == 'y':
receiver_email = input("Your e-mail: ")
msg['From'] = sender_email
msg['To'] = receiver_email
print(
'Goodbye, an email has been sent to ' + receiver_email + " and you will receive a copy for data from your searched cities there")
server.sendmail(sender_email, receiver_email, msg.as_string())
sys.exit()
else:
print('Goodbye')
sys.exit()
To send many items you have to keep them on list
results = []
while True:
results.append({
'city': city,
'degrees': degrees,
'humidity': humidity
})
And then you can add it to message
for item in results:
html_message += """City: {}<br>
Temperature: {:.1f}°C<br>
Humidity: {}%<b>
""".format(item['city'], item['degrees'], item['humidity'])
Full working code with other changes
import datetime
import requests
import sys
import smtplib
import ad_pw
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_mail(name_of_user, receiver_email, results):
# HTML
html_message = """\
<html>
<head></head>
<body>
<p>Hi, {}<br>
Here is the data from your weather search:<br>
<br>
""".format(name_of_user)
#---
for item in results:
html_message += """City: {}<br>
Temperature: {:.1f}°C<br>
Humidity: {}%<b>
""".format(item['city'], item['degrees'], item['humidity'])
#---
html_message += "</p>\n</body>\n</html>"
#---
print(html_message)
# Email
msg = MIMEMultipart('alternative')
msg = MIMEText(html_message, "html")
sender_email = ad_pw.email_address
msg['From'] = sender_email
msg['To'] = receiver_email
#Email
password = ad_pw.email_password
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg.as_string())
def display(text_1='afternoon', text_2='you might need a jacket'):
print("\nGood {} {}.".format(text_1, name_of_user))
print("\nThe date today is: {}".format(date))
print("The current time is: {}".format(time))
print("The humidity is: {}%".format(humidity))
print("Latitude and longitude for {} is {},{}".format(city, latitude, longitude))
print("The temperature is a mild {:.1f}°C, {}.".format(degrees, text_2))
# --- main ---
#Input
name_of_user = input("What is your name?: ")
results = []
#Loop
while True:
#Input
city = input('City Name: ')
# API
api_address='http://api.openweathermap.org/data/2.5/weather?appid=0c42f7f6b53b244c78a418f4f181282a&q='
url = api_address + city
json_data = requests.get(url).json()
# Variables
format_add = json_data['main']['temp']
date = str(datetime.date.today().strftime("%d %b %Y"))
time = str(datetime.datetime.now().strftime("%H:%M:%S"))
degrees = format_add - 273.15
humidity = json_data['main']['humidity']
latitude = json_data['coord']['lon']
longitude = json_data['coord']['lat']
results.append({
'city': city,
'degrees': degrees,
'humidity': humidity
})
#Program
if time > '12.00':
text_1 = 'afternoon'
else:
text_1 = 'morning'
if degrees < 20:
text_2 = 'you might need a jacket'
else:
text_2 = "don't forget to drink water."
display(text_1, text_2)
restart = input('Would you like to check another city (y/n)?: ')
if restart.lower().strip() != 'y':
receive_email = input("Do you want to receive a copy from you search (y/n)?: ")
if receive_email.lower().strip() == 'y':
receiver_email = input("Your e-mail: ")
send_mail(name_of_user, receiver_email, results)
print('Goodbye, an email has been sent to {}\
and you will receive a copy for data from your searched cities there'.format(receiver_email))
else:
print('Goodbye')
sys.exit()

python TypeError: 'float' object is not iterable in a program for monthly payment

month = 1
while month < 13:
monthly_interest_rate = annualInterestRate/12.0
min_monthlypayment = monthlyPaymentRate * balance
monthlyUnpaidBalance = balance - min_monthlypayment
updated_balance = monthlyUnpaidBalance + (monthly_interest_rate * monthlyUnpaidBalance)
print "Month: " + str(month)
print "Minimum monthly payment : " + str(round(min_monthlypayment, 2))
print "Remaining balance: " + str(round(updated_balance, 2))
balance = updated_balance
month = month + 1
print "Total paid : " + round(sum(min_monthlypayment), 2)
print "Remaining balance: " + round(updated_balance, 2)
I don't know why I'm getting this error if not using any iteration.
You are iterating when you are trying to take the sum. My suggestion would be to keep your code and store the variable in an array and then take the sum at the end so:
import numpy as np
sum_arr = np.zeros(12)
a = 0
under min_monthlypayment put: sum_arr[a] = min_monthlypayment
under month = month + 1 put: a = a+1
then to get the sum use np.sum(sum_arr)

Categories

Resources