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
Related
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}")
I have code that will take a legend of grades, and number of grades and then return values for it. I have everything right except for the semester average. Here's the formula to finding semester average:
homework average * 0.2 + quiz average * 0.2 + project average * 0.6.
My code works well with homework averages, quiz averages, and project averages but not with semester average.
Here's what I have written:
def get_header():
gb_data = open('gb_data.txt','r')
header = gb_data.readline()
return header.strip()
def get_content():
gb_data = open('gb_data.txt','r')
content = gb_data.readlines()
del content[0]
return content
hw_pos = []
project_pos = []
quiz_pos = []
header_list = get_header()
header_list = header_list.split(", ")
header_list_index = enumerate(header_list)
for index, target in header_list_index:
if target == "hw":
hw_pos.append(index)
elif target == "quiz":
quiz_pos.append(index)
elif target == "project":
project_pos.append(index)
content_list = get_content()
avg_dict = {}
for element in content_list:
element = element.strip().split(", ")
name = element[0] + ', ' + element[1]
hw_avg = sum([int(element[i]) for i in hw_pos]) / len(hw_pos)
quiz_avg = sum([int(element[i]) for i in quiz_pos]) / len(quiz_pos)
project_avg = sum([int(element[i]) for i in project_pos]) / len(project_pos)
sem_avg = hw_avg * 0.2 + quiz_avg * 0.2 + project_avg * 0.6
avg_dict.update({name:(hw_avg, quiz_avg, project_avg, sem_avg)})
f = open('avg.txt', 'w')
for name, avg in avg_dict.items():
dataline = name + ": hw avg = " + str(round(avg[0], 2)) + ", quiz avg = " + str(round(avg[2], 2)) + ", proj avg = " + str(round(avg[1], 2)) + ", sem avg = " + str(round(avg[2], 2)) + "\n"
f.write(dataline)
f.close()
Here's an example of an input I put in:
last, first, hw, hw, project, quiz, hw, hw, hw, quiz, hw, hw, project
Cat, Figaro, 57, 58, 71, 93, 56, 86, 90, 99, 55, 99, 88
The top line is the legend so ignore that, my code handles that
Here's what should be given back:
Cat, Figaro: hw avg = 71.57, quiz avg = 96.0, proj avg = 79.5, sem avg = 81.21
Here's what I actually get back:
Cat, Figaro: hw avg = 71.57, quiz avg = 96.0, proj avg = 79.5, sem avg = 96.0
I want to make them match EXACTLY, down to every character. I just need to know how to round it correctly. This is NOT homework and is just a project to understand files better, I'm very close!! My name is Scarlett btw please help!!!
You have a typo this line:
dataline = name + ": hw avg = " + str(round(avg[0], 2)) + ", quiz avg = " + str(round(avg[2], 2)) + ", proj avg = " + str(round(avg[1], 2)) + ", sem avg = " + str(round(avg[2], 2)) + "\n"
It should be
dataline = name + ": hw avg = " + str(round(avg[0], 2)) + ", quiz avg = " + str(round(avg[1], 2)) + ", proj avg = " + str(round(avg[2], 2)) + ", sem avg = " + str(round(avg[3], 2)) + "\n"
instead. The calculation is fine, just the output was messed up (You printed 0, 2, 1, 2 instead of 0, 1, 2, 3). To prevent mistakes like this in the future, maybe take a look at Pandas with its column names? Pandas is probably an overkill in this case, but a very powerful tool for table-based calculations.
This should work:
from statistics import mean
legend = ['last', 'first', 'hw', 'hw', 'project', 'quiz', 'hw', 'hw', 'hw', 'quiz', 'hw', 'hw', 'project']
grades = ['Cat', 'Figaro', 57, 58, 71, 93, 56, 86, 90, 99, 55, 99, 88]
hw_avg = mean([g for l, g in zip(legend, grades) if l == 'hw'])
quiz_avg = mean([g for l, g in zip(legend, grades) if l == 'quiz'])
project_avg = mean([g for l, g in zip(legend, grades) if l == 'project'])
sem_avg = hw_avg * 0.2 + quiz_avg * 0.2 + project_avg * 0.6
print(f'{grades[0]}, {grades[1]}: hw avg = {hw_avg:.2f}, quiz avg = {quiz_avg:.2f}, project avg = {project_avg:.2f}, sem avg = {sem_avg:.2f}')
It gives me the following:
Cat, Figaro: hw avg = 71.57, quiz avg = 96.00, project avg = 79.50, sem avg = 81.21
Note that I'm just using statistics.mean as it makes the code cleaner. But you could do the same with a method like yours.
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]))) ) )
I'm a beginner coding in python. I really don't understand what this error refers to. Any help will be greatly appreciated.
the code is supposed to calculate the taxes of people in a certain country as follows:
Yearly Income: 0 - 1000
Tax Rate: 0%
Yearly Income: 1,001 - 10,000
Tax Rate: 10%
Yearly Income: 10,001 - 20,200
Tax Rate: 15%
Yearly Income: 20,201 - 30,750
Tax Rate: 20%
Yearly Income: 30,751 - 50,000
Tax Rate: 25%
Yearly Income: Over 50,000
Tax Rate: 30%
my code:
def calculate_tax(pDict):
if type(pDict) is dict:
try:
length = len(pDict)
count = 0
#decleration of new updated dictionary
dict_list = {}
while count<length:
#calculate yearly tax
#countdown of values in the dictionary until the last value
totals = list(pDict.values())[count]
totals = int(totals)
names = list(pDict.keys())[count]
#decleration of variable to store tax
tTax = 0
if totals < 1000:
tTax = totals * 0
elif totals > 1000 and totals<= 10000:
tTax = 1000 * 0
totals = totals - 1000
tTax = tTax + totals * 0.1
elif totals > 10000 and totals <=20200:
tTax = 1000 * 0
tTax = tTax + 9000 * 0.1
totals=totals-10000
tTax = tTax + totals * 0.15
elif totals >20200 and totals <= 30750:
tTax = 1000 * 0
tTax = tTax + 9000 * 0.1
tTax = tTax + 10200 * 0.15
totals=totals-20200
tTax = tTax + totals * 0.2
elif totals>30750 and totals<=50000:
tTax = 1000 * 0
tTax = tTax + 9000 * 0.1
tTax = tTax + 10200 * 0.15
tTax = tTax + 10550 * 0.2
totals=totals-30750
tTax = tTax + totals * 0.25
else:
tTax = 1000 * 0
tTax = tTax + 9000 * 0.1
tTax = tTax + 10200 * 0.15
tTax = tTax + 10550 * 0.2
tTax = tTax + 19250 * 0.25
totals=totals-50000
tTax = tTax + totals * 0.3
dict_list.setdefault(names,tTax)
count = count + 1
return dict_list
except(attributeError,TypeError):
raise ValueError('The provided input is not a dictionary')
else:
print("only dict type values allowed")
the code used to test if my code works:
from unittest import TestCase
class CalculateTaxTests(TestCase):
def test_it_calculates_tax_for_one_person(self):
result = calculate_tax({"James": 20500})
self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}")
def test_it_calculates_tax_for_several_people(self):
income_input = {"James": 20500, "Mary": 500, "Evan": 70000}
result = calculate_tax(income_input)
self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result,
msg="Should return {} for the input {}".format(
{"James": 2490.0, "Mary": 0, "Evan": 15352.5},
{"James": 20500, "Mary": 500, "Evan": 70000}
)
)
def test_it_does_not_accept_integers(self):
with self.assertRaises(ValueError) as context:
calculate_tax(1)
self.assertEqual(
"The provided input is not a dictionary.",
context.exception.message, "Invalid input of type int not allowed"
)
def test_calculated_tax_is_a_float(self):
result = calculate_tax({"Jane": 20500})
self.assertIsInstance(
calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict")
self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.")
def test_it_returns_zero_tax_for_income_less_than_1000(self):
result = calculate_tax({"Jake": 100})
self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000")
def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self):
with self.assertRaises(ValueError, msg='Allow only numeric input'):
calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5})
def test_it_return_an_empty_dict_for_an_empty_dict_input(self):
result = calculate_tax({})
self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict')
Please help:-)
For reference, the complete exception message from the failing test is as follows:
ERROR: test_it_does_not_accept_integers (__main__.CalculateTaxTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "calculate_tax_test.py", line 27, in test_it_does_not_accept_integers
context.exception.message, "Invalid input of type int not allowed"
AttributeError: '_AssertRaisesContext' object has no attribute 'exception'
The failing test is this:
def test_it_does_not_accept_integers(self):
with self.assertRaises(ValueError) as context:
calculate_tax(1)
self.assertEqual(
"The provided input is not a dictionary.",
context.exception.message, "Invalid input of type int not allowed"
)
The problem is that the assertion after calculate_tax is in the wrong place. If an exception is raised in calculate_tax, the assertion will be skipped. If no exception is raised, the assertion will fail. The assertion will therefore never pass.
The fix is to un-indent the assertion to move it out of the with statement. For clarity I've also inserted a blank line:
def test_it_does_not_accept_integers(self):
with self.assertRaises(ValueError) as context:
calculate_tax(1)
self.assertEqual(
"The provided input is not a dictionary.",
context.exception.message, "Invalid input of type int not allowed"
)
The with self.assertRaises(...) statement can catch an exception if one gets raised by the call to calculate_tax. If this happens, the exception detail is then left in context, and your assertion would then be able to test whether the exception was as you expected.
However, even after making this change, the test still fails, because calculate_tax(1) doesn't raise a ValueError. I'll leave it up to you to fix this.
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)