Writing a program that takes in a shopping list of dataclass items that fit one of three categories. The function is supposed to calculate the total based on the items, quantity, and state's sales tax. The only issue is, the way my function performs now, its outputting a result that isn't what's expected. It is giving me the proper total; However, the total isn't compensating for the tax I'm trying to calculate. Any help would be greatly appreciated.
class Category(enum.Enum):
wic = 0
clothing = 1
other = 2
#dataclass
class item:
name: str
price: float
quantity: int
category: Category
def total_calculator(shopping_cart, a_state):
tax_rate, subtotal, total, cloth_total, wic_total, other_total = 0, 0, 0, 0, 0, 0
if a_state == "Massachusetts":
tax_rate = 0.0675
elif a_state == "Maine":
tax_rate = 0.0550
else:
tax_rate = 0
for item_ in shopping_cart:
if item_.category == Category.wic:
wic_total += (item_.price * item_.quantity)
# Starts the calculation sequence for clothing based on state
elif item_.category == Category.clothing:
cloth_total += item_.price * item_.quantity + (item_.price * tax_rate)
if item_.category == Category.clothing and a_state == "Massachusetts":
if item_.price >= 175:
cloth_total += item_.price * item_.quantity + (item_.price * 0.0625)
else:
cloth_total += (item_.price * item_.quantity)
# Starts the calculation sequence for other based on state
print(cloth_total)
elif item_.category == Category.other:
other_total += item_.price * item_.quantity + (item_.price * tax_rate)
total = wic_total + cloth_total + other_total
return total
Related
So, I'm stuck at the moment.
I'm creating a program to calculate the complete sale if multiple, or singular, items are purchased. The program is also supposed to calculate a discount threshold and a state-sale's tax with the purchase. I can get the program to function, however, my end result is 0.0 dollars despite entries made. At this point, I can identify it is multiplying SOMETHING by 0, which I assume is the tax input, but I am at a total loss on how to correct this issue. Below is the code used.
#declarations
A_STATE_TAX = float(.056)
C_STATE_TAX = float(.029)
N_STATE_TAX = float(.05125)
U_STATE_TAX = float(.047)
state = ''
tax = float()
completeSale = ()
sockPrice = int(5)
sandalPrice = int(10)
shoePrice = int(20)
bootPrice = int(30)
quantityShoes = int()
quantitySocks = int()
quantityBoots = int()
quantitySandals = int()
quantityTotal = int()
quantityTotal = int(quantityTotal)
basePriceSocks = (quantitySocks * sockPrice)
basePriceShoes = (quantityShoes * shoePrice)
basePriceBoots = (quantityBoots * bootPrice)
basePriceSandals = (quantitySandals * sandalPrice)
baseTotal = int(basePriceSocks + basePriceShoes + basePriceBoots +basePriceSandals)
discount = float()
discountAnswer = (baseTotal * discount)
purchaseWithoutTax = baseTotal - (baseTotal * discount)
taxAnswer = purchaseWithoutTax * tax
#mainbody
print("This algorithm will calculate your purchase.")
#housekeeping()
print("How many shoes do you wish to purchase?")
input(quantityShoes)
print("How many socks?")
input(quantitySocks)
print("Boots?")
input(quantityBoots)
print("And sandals?")
input(quantitySandals)
#purchaseinfo()
quantityTotal = (quantityShoes + quantityShoes + quantityBoots + quantitySandals)
if quantityTotal < 6:
discount = 0
elif quantityTotal > 6 and quanityTotal < 10:
discount = .10
else:
discount = .20
purchaseWithoutTax = baseTotal - (baseTotal * discount)
#stateTax()
print("Please choose the following state: Arizona, New Mexico, Colorado or Utah.")
input(str(state))
if state == "arizona":
tax = A_STATE_TAX
elif state == "new mexico":
tax = N_STATE_TAX
elif state == "colorado":
tax = C_STATE_TAX
else:
tax = U_STATE_TAX
completeSale = (purchaseWithoutTax * tax) - taxAnswer
#endOfJob()
print(format(completeSale, '.2f'))
print("Your total is ", format(completeSale, '.2f'), " dollars.")
print("Thank you for your patronage.")
The main issue is that your baseTotal = 0 initially. And baseTotal = 0 because your quantities (e.g., quantityShoes) are initially 0. You shouldn't initialize values with int(), you should use 0 instead because it is more explicit. You multiply values with baseTotal so in the end you will get 0.
And as another answer mentions, you are using input incorrectly. For numeric quantities, you should convert the result of input to float or int, because input returns strings. You should also save the output to a variable name.
quantityShoes = int(input("How many shoes?"))
You can clean up your code by using dictionaries. That might help with debugging. Instead of having multiple quantity___ variables, you can use a dictionary that stores quantities (and prices, taxes, etc.).
state_taxes = {
"arizona": 0.056,
"colorado": 0.029,
"new mexico": 0.05125,
"utah": 0.047,
}
prices = {
"sock": 5,
"sandal": 10,
"shoe": 20,
"boot": 30,
}
input() doesn't work the way you used it. The argument that goes in input()
is printed before the user gives input. You did the equivalent of:
quantityShoes = int()
print("How many shoes do you wish to purchase?")
input(quantityShoes)
The first line sets quantityShoes equal to the default integer, which is 0. The second line prints that text. The third line line prints that number and waits for user input. You want to do something like:
quantityShoes = int(input("How many shoes do you wish to purchase?"))
The issue i am having is getting the value of a returned item to update from different functions within a main function.
I have tried syntax to see if that changed anything, but I am not sure what needs to happen to get (in this case: the count and total).
I have also tried setting the functions = count, total but that returned an error.
def main():
terminate = False
print("Welcome to the self-checkout system at Wake-Mart.")
count, total = scan_prices()
print('')
disc = discount(count, total)
print('')
promo = promotion(count, total)
balance = total
def scan_prices():
total = 0
count = 0
prices = float(input("Enter the price of the first item:"))
while prices > 0:
count +=1
total = total + prices
print("Number of items:", count, "Total:", total)
prices = float(input("Eneter the price of the next item [or 0 to stop]:"))
while prices < 0:
print("Price cannot be negative.")
prices = float(input("Eneter the price of the next item [or 0 to stop]:"))
if prices > 0:
count +=1
total = total + prices
print("Number of items:", count, "Total:", total)
prices = float(input("Eneter the price of the next item [or 0 to stop]:"))
continue
return count, total
def discount(count, total):
if count >= 10:
print("You've got a 10% discount for buying 10 items or more.")
total = total * .9
print("Number of items:", count, "Total:", total)
return total
def promotion(count, total):
if total >= 50:
card = input(print("Do you want to buy a $50 gift card for $40 [y/n]:"))
if card == 'Y' or 'y':
print("Thank you for buying a giftcard.")
count +=1
total = (total * .9) + 40
print("Number if items:", count, "Total:", total)
else:
print("Thank for your purchases.")
print("Number if items:", count, "Total:", (total * .9))
return count, total
main()
I am just wanting the total and count to be updated as I move from one function execution to the next within the main function.
It looks like your main should take the return of one function and pass it to the next:
def main():
terminate = False
print("Welcome to the self-checkout system at Wake-Mart.")
count, total = scan_prices()
print('')
total = discount(count, total)
print('')
count, total = promotion(count, total)
balance = total
I dont understand why the code doesnt work and they have repeated the questions to me 4 times. and say that float is not callable. i have tried doing this for quite awhile but i dont seem to get anything at all. is there any easier way for python3? I just learnt this language 2 weeks ago. its not a whole new world to me but many of the things i am not familiar with. such as indentation
def get_taxi_info():
flag_down = float(input("What's the flag-down fare: $"))
within = float(input("What's the rate per 400 meters within 9.8km? $"))
beyond = float(input("What's the rate per 350 meters beyond 9.8km? $"))
distance = float(input("What's the distance traveled (in meters)? "))
peak = input("Is the ride during a peak period? [yes/no]")
mid6 = input("Is the ride between midnight and 6am? [yes/no]")
location = input("Is there any location surcharge? [yes/no]")
surloca = float(input("What's the amount of location surcharge?"))
return (flag_down, within, beyond, distance, peak == 'yes', mid6 == 'yes', location == 'yes', surloca)
def calculate_taxi_fare():
dist = get_taxi_info()
if dist[3] > 9800:
extra = (dist[3] - 9800) % 350
if extra == 0:
a = (extra//350) + 22
else:
a = (extra//350) + 23
return a
elif dist[3] <= 9800:
extra = (dist[3] - 1000) % 400
if extra == 0:
a = (extra//400)
else:
a = (extra//400) + 1
return a
def peakornot():
peak = get_taxi_info()
if peak[4] == True and peak[5] == False:
surcharge = 1.25
return surcharge
elif peak[4] == False and peak[5] == True:
surcharge = 1.50
return surcharge
taxifare = calculate_taxi_fare()
info = get_taxi_info()
peak1 = peakornot()
taxifare = calculate_taxi_fare()
if info[6] == True:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
elif info[6] == False:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
The function calculate_taxi_fare returns a float, so on this line taxifare is a float
taxifare = calculate_taxi_fare()
Therefore you cannot say taxifare() because it looks like a function call, so you can just use for example
info[1] * taxifare
So I am quite new to python and have been working on this assignment for a week now on and off and can't quite get it to run correctly. I am now getting errors that tell me the function get_in_code is not defined although I've defined it. Any help would be greatly appreciated!
SENTINEL = 'XXX'
DAY_CHARGE = 1500.00
#Define get_days
def get_days():
good_data = False
while not good_data:
try:
n_days = int(input("Please enter the number of days you stayed: "))
except ValueError:
print("Error, Bad Data")
else:
if n_days > 0:
good_data = True
else:
print("This is bad data, please re enter data")
return n_days
#define get_cost(p)
def get_cost():
cost = float(input("Please enter the cost for the procedures: "))
while cost < 0:
print("Procedure cost cant be negative: ")
cost = float(input("Please enter the cost for the procedures: "))
return cost
#define med cost
def med_cost():
med_cost = float(input("Enter the cost of your medicine: "))
while med_cost < 0:
print("Medicine cost cant be negative: ")
med_cost = float(input("Enter the cost of your medicine: "))
return med_cost
#Find day cost
def find_day_cost(in_code, n_days):
day_cost = n_days * DAY_CHARGE
if in_code == 'ZH':
p_day_cost = day_cost * 0.20
in_day_cost = day_cost *0.80
elif in_code == 'HH':
p_day_cost = day_cost * 0.10
in_day_cost = day_cost * 0.90
elif in_code == 'CH':
p_day_cost = day_cost * 0.25
in_day_cost = day_cost * 0.75
else:
p_day_cost = day_cost
in_day_cost = 0
return p_day_cost, in_day_cost
#find procedure cost
def find_proc_cost(in_code, cost):
if in_code == 'ZH':
p_proc_cost = 0
in_proc_cost = cost
elif in_code == 'HH':
p_proc_cost = cost * 0.10
in_proc_cost = cost * 0.90
elif in_code == 'CH':
p_proc_cost = cost * 0.50
in_proc_cost = cost * 0.50
else:
p_proc_cost = cost
in_proc_cost = 0
return p_proc_cost, in_proc_cost
#find medicine cost
def find_med_cost(in_code, med_cost):
if in_code == 'ZH':
p_med_cost = 0
in_med_cost = med_cost
elif in_code == 'HH':
p_med_cost = med_cost * 0.10
in_med_cost = med_cost * 0.90
elif in_code == 'CH':
p_med_cost = med_cost * 0.50
in_med_cost = med_cost * 0.50
else:
p_med_cost = med_cost
in_med_cost = 0
return p_med_cost, in_med_cost
#Display pat_info
def display_pat_info(pat_name, in_name):
print("City Hospital - Patient Invoice")
print("Patient Name: ", pat_name)
print("Insurance: ", in_name)
#display day cost
def display_day_cost(p_day_cost, in_day_cost):
print("Patient Day Cost: ", p_day_cost,"\tInsurance Day Cost: ", in_day_cost)
#display procedure cost
def display_proc_cost(p_proc_cost, in_proc_cost):
print("Patient Procedure Cost: ", p_proc_cost, "\tInsurance Procedure Cost: ", in_proc_cost)
#display medicine cost
def display_med_cost(p_med_cost, in_med_cost):
print("Patient Medicine Cost: ", p_med_cost, "\tInsurce Medicine Cost: ", in_med_cost)
#Display totals
def display_totals(total_pat, total_in):
print("Total Billed To Patient: ", total_pat, "\tTotal Billed To Insurance: ", total_in, "\tTotal Bill: ", (total_pat + total_in))
#display day_totals
def display_day_totals(total_zip, total_happy, total_cheap, total_pat):
print("City Hospital - End Of Day Billing Report")
print("Total Dollar Amount Billed Today: ", total_zip+total_happy+total_cheap+total_pat)
print("Total Billed To Zippy Healthcare: ", total_zip)
print("Total Billed To Happy Healthcare: ", total_happy)
print("Total Billed To Cheap Healthcare: ", total_cheap)
print("Total Billed To Uninsured: ", total_pat)
#display day_counts()
def display_day_counts(zip_count, happy_count, cheap_count, no_in_count):
print("The total amount of Zippy Healthcare patients is: ", zip_count)
print("The total amount of Happy Healthcare patients is: ", happy_count)
print("The total amount of Cheap Healthcare patients is: ", cheap_count)
print("The total amount of Uninsured patients is: ", no_in_count)
#def main
def main():
#Counters and accumulators
total_zip= 0.00
total_cheap= 0.00
total_happy= 0.00
total_pat= 0.00
zip_count= 0
cheap_count= 0
happy_count= 0
no_in_count= 0
total_in = 0
#Open file
try:
Pat_File = open('PatientBill.txt', 'w')
except ValueError:
print("*****ERROR***** - Corrupt File")
else:
file_exist = True
#Priming read
pat_name = input("Please enter the patients name: (XXX to stop program)")
#Processing loop
while pat_name != SENTINEL:
#Input data
in_code = get_in_code()
num_days = get_days()
proc_cost = get_cost()
med_cost = med_cost()
#find each cost
pat_day, insure_day = find_day_cost(in_code, num_days)
pat_proc, insure_proc = find_proc_cost(in_code, proc_cost)
pat_med, insure_med = find_med_cost(in_code, med_cost)
#update accumulators and totals
total_pat += pat_day + pat_proc + pat_med
if in_code == 'ZH':
zip_count += 1
total_zip += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Zippy Healthcare'
elif in_code == 'HH':
happy_count += 1
total_happy += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Happy Healthcare'
elif in_code == 'CH':
cheap_count += 1
total_cheap += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Cheap Healthcare'
else:
no_in_count += 1
in_name = 'Uninsured'
total_in = total_zip + total_happy + total_cheap
#displays patients invoice
display_pat_info(pat_name,in_name)
display_day_cost(pat_day, insure_day)
display_proc_cost(pat_proc, insure_proc)
display_med_cost(pat_med, insure_med)
display_totals(pat_day + pat_proc + pat_med, insure_day + insure_proc + insure_med)
#Write output to file
if file_exist:
Pat_File.write(pat_name, pat_day+pat_med+pat_proc )
#Get next patients name
pat_name = input("Please enter the patients name: (XXX to stop program)")
#Close the output file
if file_exist:
Pat_File.close()
#display the accumlators and totals
display_day_totals(total_zip, total_happy, total_cheap, total_pat)
display_day_counts(zip_count,happy_count,cheap_count,no_in_count)
#define get_in_code
def get_in_code():
in_code = input("Please enter one of the insurance codes, ZH, CH, HH, XX")
while in_code not in ('ZH', 'HH', 'CH', 'XX'):
print("***Please enter a proper insurance code***")
in_code = input("Please enter one of the insurance codes, ZH, CH, HH, XX")
return in_code
main()
Python is a interpreted language. You need to define function prior to its usage. Just move a function definitions at the top of a file.
The problem is also with indentation. You're defining your methods inside while, just after a return statement. Actual functions aren't defined at all - interpreter doesn't reach those lines.
Besides, the code is "dirty". Split the code into separate classes/modules. Create well defined areas of responsibility, that would improve the code and it'll be easier to work with it.
Quick question:
I want to call a main function without any arguments, and within the main function, I have several other functions that do have arguments. How would I go about doing this?
Here are the multiple functions:
# Takes the Portfolio dictionay, unpacks the multiple tuples, and calculates
# the total price of the shares at time of purchase
def total_purchase_price(portfolio):
totalprice = 0
totalpurprice = 0
for item in portfolio:
purdate, purprice, numshares, sym, curprice = item
totalprice += purprice * numshares
totalpurprice = totalprice
return totalpurprice
# Takes the Portfolio dictionay, unpacks the multiple tuples, and calculates
# the current total value of the shares
def total_value(portfolio):
totalprice = 0
totalvalueprice = 0
for item in portfolio:
purdate, purprice, numshares, sym, curprice = item
totalprice += curprice * numshares
totalvalueprice = totalprice
return totalvalueprice
# Takes the previous two functions, and subtracts them to get the total
# gain/lost of the shares
def total_gain(total_purchase_price, total_value, portfolio):
gainlost = total_value - total_purchase_price
return gainlost
ex. What I have right now (note: I know this won't work, just there for what I want, as each function returns a value):
def testQ1(total_purchase_price, total_value, total_gain, portfolio):
print("Total Cost =", total_purchase_price)
print("Current Value =", total_value)
print("Total gain/lost =", total_gain)
return
ex. What I want to achieve:
def testQ2():
total_purchase_price(portfolio)
total_value(portfolio)
total_gain(total_purchase_price, total_value, portfolio)
print("Total Cost =", total_purchase_price)
print("Current Value =", total_value)
print("Total gain/lost =", total_gain)
return
How would I do this? Thanks
Using a class might be easier:
class PortfolioParser:
def __init__(self, portfolio):
self.portfolio = portfolio
self.price = self.total_purchase_price()
self.value = self.total_value()
self.gain = self.total_gain()
def total_purchase_price(self):
# Takes the Portfolio dictionay, unpacks the multiple tuples, and calculates
# the total price of the shares at time of purchase
totalprice = 0
totalpurprice = 0
for item in self.portfolio:
purdate, purprice, numshares, sym, curprice = item
totalprice += purprice * numshares
totalpurprice = totalprice
return totalpurprice
def total_value(self):
# Takes the Portfolio dictionay, unpacks the multiple tuples, and calculates
# the current total value of the shares
totalprice = 0
totalvalueprice = 0
for item in self.portfolio:
purdate, purprice, numshares, sym, curprice = item
totalprice += curprice * numshares
totalvalueprice = totalprice
return totalvalueprice
def total_gain(self):
# Takes the previous two functions, and subtracts them to get the total
# gain/lost of the shares
return self.value- self.price
def testQ2(self):
print("Total Cost = {0}\nCurrent Value = {1}\nTotal Gains = {2}".format(self.price, self.value, self.gain))
And then you would use it like so:
myPortfolio = # The portfolio to parse
parser = PortfolioParser(myPortfolio)
parser.testQ2()
portfolio is the only argument that is not calculated within testQ2. You need to have a global value for it, or read it in (maybe in another function). After they have been calculated return the values in an appropriate order.
def testQ2():
portfolio = getPortfolio()
tp = total_purchase_price(portfolio)
tv = total_value(portfolio)
tg = total_gain(tp, tv, portfolio)
print("Total Cost =", tp)
print("Current Value =", tv)
print("Total gain/lost =", tg)
return portfolio, tp, tv, tg