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.
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}")
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]))) ) )
How do I repeat this code 5000 times? Can't seem to make it work. How can I do this without running a loop?
age = ['<=20', '21-30', '31-40', '41-50', '51-60', '61-65', '>=66']
number_of_people = np.array([105770, 1170176, 1797410, 1256255, 692903, 88260, 7362])
mean_salary = np.array([17487, 32481, 47044, 56863, 59514, 76572, 114779])
sd = np.array([7459, 18207, 37225, 65919, 103232, 137916, 360839])
total_population = 5118136
samplesize = 200
sample200 = [(num/total_population) * samplesize for num in number_of_people]
sample200 = np.round(sample200)
#Adding one person to age group of '>=66' for sample size of 200
newsample200 = [4, 46, 70 , 49, 27, 3, 1]
sample200dist = np.array([])
for i in range(len(newsample200)):
for j in range(newsample200[i]):
new_dist = np.random.normal(mean_salary[i], sd[i])
if new_dist > 0.0:
sample200dist = np.append(sample200dist, new_dist)
else:
sample200dist = np.append(sample200dist, abs(new_dist))
print('The median monthly salary of sample size 200 is:', np.median(sample200dist))
I am trying to solve an online question using binary search (bisection search?) and I am uncertain where my code is wrong, my answers vary from the expected answer by a bit more than comfortable for me. I would really appreciate to know where I am off-course, as well as pointers for the future.
I am given an annual interest rate and an initial balance. I am also expected to select a small enough step so I can increment to the cent.
My code is like this:
startbalance = input('Balance: ')
annualInterestRate = input('annualInterestRate: ')
monthlyInterestRate = annualInterestRate / 12.0
balance = startbalance
step = 0.01
lowbound = balance / 12.0
highbound = (balance * (1 + monthlyInterestRate)**12) / 12.0
monthlyPayment = (lowbound + highbound) / 2.0
while (monthlyPayment - balance) >= step:
for month in range(0, 12):
balance -= monthlyPayment
balance = balance + ((1 + monthlyInterestRate) * balance)
if balance < 0:
highbound = monthlyPayment
balance = startbalance
elif balance > 0:
lowbound = monthlyPayment
balance = startbalance
print 'Lowest Payment: ', round(monthlyPayment, 2)
Testing my code with the values provided in cases, I have the following:
With an annual interest rate of 0.2
and a balance of 320000,
My result: 29591.88 (incorrect, the answer should be 29157.09)
With an annual interest rate of 0.18
and a balance of 999999,
My result: 91484.0 (incorrect, the answer should be 90325.03)
I think I am just a little bit off and I would really appreciate some setting-straight.
Thanks!
Fixed it (thanks, z0k!):
startbalance = input('Balance: ')
annualInterestRate = input('annualInterestRate: ')
monthlyInterestRate = annualInterestRate / 12.0
monthlyInterestRate = annualInterestRate / 12.0
startbalance = balance
step = 0.01
lowbound = startbalance / 12.0
highbound = (startbalance * (1 + monthlyInterestRate)**12) / 12.0
monthlyPayment = (lowbound + highbound) / 2.0
while (abs(startbalance)) >= step:
startbalance = balance
for month in range(0, 12):
startbalance -= monthlyPayment
startbalance = startbalance + ((monthlyInterestRate) * startbalance)
if startbalance < 0:
highbound = monthlyPayment
if startbalance > 0:
lowbound = monthlyPayment
monthlyPayment = (lowbound + highbound) / 2.0
print 'Lowest Payment: ', round(monthlyPayment, 2)