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}")
Related
I am trying to use 'for loop' to write to a file in python dynamically, but I do not know how to calculate to write dynamically. I would appreciate if I get some help on this.
def earnings(name, age, salary):
AnnualRate = 0.05
outFile = open('yearly_earnings.txt', 'w')
outFile.write('Prepared by: Amornchot Singh')
outFile.write('Age Salary Total')
n = 26
for n in range(66):
ageLimit = 65
i = 26
totalEarned = 0
for i in range(ageLimit+1):
totalEarned += salary * (1+AnnualRate)
print('summary for ' + name)
print('Starting salary at age ' + age + ' was ' + salary)
print('Salary increases were 5.0% per year')
print('Total accumulated earnings by age 65 is {:,.2f}'.format(totalEarned))
print("To view yearly data go to 'yearly_earnings.txt'")
print("'Thank you for using the earnings() function.'")
First of all remove all redundant lines of code
Call the function
Don't forget to close the file after writing something, otherwise it
will not save the data in your file
Python don't allow to add integer with string so convert the integer
into str before concatenating
print('Starting salary at age ' + str(age) + ' was ' + str(salary))
Here is full code
def earnings(name, age, salary):
AnnualRate = 0.05
outFile = open('yearly_earnings.txt', 'w')
outFile.write('Prepared by: Amornchot Singh')
outFile.write('Age Salary Total')
ageLimit = 65
i = 26
totalEarned = 0
for i in range(ageLimit+1):
totalEarned += salary * (1+AnnualRate)
outFile.close()
print('summary for ' + name)
print('Starting salary at age ' + str(age) + ' was ' + str(salary))
print('Salary increases were 5.0% per year')
print('Total accumulated earnings by age 65 is {:,.2f}'.format(totalEarned))
print("To view yearly data go to 'yearly_earnings.txt'")
print("'Thank you for using the earnings() function.'")
earnings("Tariq", 20, 500000)
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)
the purpose of this file is to ask the user for values, calculates the values for different purposes, and then display data.
Everything works besides the while loop. It is supposed to make the value of servings go down if the Grand_Weight_Mix_Total is > 450.
The while loops checks to see if Grand_Weight_Mix_Total is above 450, if it is, then the value of servings should go down 1 and then the while loop is executed again. The loop will break once the value of servings is below 450.
customerName = input("Customer Name:\n")
mixName = input("Mix Name:\n")
L_Citrulline_Mallate = int(input("Amount of L-Citrulline Malate (2:1) per serving(grams):\n"))
Beta_Alanine = int(input("Amount of Beta Alanine per serving(grams):\n"))
Caffeine_Anhydrous = float(input("Amount of Caffeine Anhydrous per serving(milligrams):\n"))/1000
Betaine_Anhydrous = int(input("Amount of Betaine Anhydrous per serving(grams):\n"))
Taurine = int(input("Amount of Taurine per serving(grams):\n"))
Creatine_HCL = int(input("Amount of Creatine_HCL per serving(grams):\n"))
L_Theanine = float(input("Amount of L-Theanine per serving(milligrams):\n"))/1000
L_Tyrosine = int(input("Amount of L-Tyrosine per serving(grams):\n"))
Sodium_Bicarbonate = float(input("Amount of Sodium_Bicarbonate per serving(milligrams):\n"))/1000
servings = 35
#Mix Total
Mix_Total = float(L_Citrulline_Mallate + Beta_Alanine + Caffeine_Anhydrous + Betaine_Anhydrous + Taurine + Creatine_HCL + L_Theanine + L_Tyrosine + Sodium_Bicarbonate)* servings
#Servings Total
Serving_Total = float(L_Citrulline_Mallate + Beta_Alanine + Caffeine_Anhydrous + Betaine_Anhydrous + Taurine + Creatine_HCL + L_Theanine + L_Tyrosine + Sodium_Bicarbonate)
#Flavor
Flavor_Weight = float(Serving_Total/.8)
Flavor_Weight_Total = float(Flavor_Weight * servings)
Grand_Serving_Total_Weight = float(Flavor_Weight + Serving_Total)
Grand_Weight_Mix_Total = float(Grand_Serving_Total_Weight * servings)
#while
while (Grand_Weight_Mix_Total > 450):
servings = servings - 1
if Grand_Serving_Total_Weight <= 449:
break
print('Servings loop value', servings)
#Print
print (f'Customer: {customerName}')
print (f'Mix Name: {mixName}')
print (f'Servings: {servings}')
print (f'L-Citrulline Malate: {L_Citrulline_Mallate}')
print (f'Beta Alanine: {Beta_Alanine}')
print (f'Caffeine Anhydrous: {Caffeine_Anhydrous}')
print (f'Betaine Anhydrous: {Betaine_Anhydrous}')
print (f'Taurine: {Taurine}')
print (f'Creatine HCL: {Creatine_HCL}')
print (f'L-Theanine: {L_Theanine}')
print (f'L-Tryosine: {L_Tyrosine}')
print (f'Sodium Bicarbonate: {Sodium_Bicarbonate}')
#Calculate total grams needed for each ingredent
Total_L_Citrulline_Mallate = int(L_Citrulline_Mallate * servings)
Total_Beta_Alanine = int(Beta_Alanine * servings)
Total_Caffeine_Anhydrous = float(Caffeine_Anhydrous * servings)
Total_Betaine_Anhydrous = int(Betaine_Anhydrous * servings)
Total_Taurine = int(Taurine * servings)
Total_Creatine_HCL = int(Creatine_HCL * servings)
Total_L_Theanine = float(L_Theanine * servings)
Total_L_Tyrosine = int(L_Tyrosine * servings)
Total_Sodium_Bicarbonate = float(Sodium_Bicarbonate * servings)
#Print total grams of each ingredient
print("L-Citrulline Mallate Total Grams:", Total_L_Citrulline_Mallate)
print("Beta Alanine Total Grams:", Total_Beta_Alanine)
print("Caffeine Anhydrous Total Grams:", Total_Caffeine_Anhydrous)
print("Betaine Anhydrous Total Grams:", Total_Betaine_Anhydrous)
print("Taurine Total Grams:", Total_Taurine)
print("Creatine HCL Total Grams:", Total_Creatine_HCL)
print("L-Theanine Total Grams:", Total_L_Theanine)
print("L-Tyrosine Total Grams:", Total_L_Tyrosine)
print("Sodium Bicarbonate Total Grams:", Total_Sodium_Bicarbonate)
print("Mix serving weight (flavor not included): ", Serving_Total)
print("Mix total wight: ", Mix_Total)
print("Flavor Weight", Flavor_Weight)
print("Flavor Weight Total", Flavor_Weight_Total)
print("Grand Total Serving Weight", Grand_Serving_Total_Weight)
print("Grand Total Mix Weight", Grand_Weight_Mix_Total)
I think you didn't understand this line:
Grand_Weight_Mix_Total = float(Grand_Serving_Total_Weight * servings)
This line mean that Grand_Weight_Mix_Total is the multiply of Grand_Serving_Total_Weight * servings in this moment, and it gonna stay like this until you change Grand_Serving_Total_Weight again
It's not getting updated when you change servings, you need to reassign the value your self by:
while (Grand_Weight_Mix_Total > 450):
servings = servings - 1
Grand_Weight_Mix_Total = float(Grand_Serving_Total_Weight * servings)
print('Servings loop value', servings)
also notice that i remove this
if Grand_Serving_Total_Weight <= 449:
break
which is redudent because of the while loop
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]))) ) )
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)