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?"))
Related
I have been experimenting with creating an investment calculator, and I want to print the annual totals as well as the annual compounded interest. It's doing the annual totals fine, but not the annual interest. My inputs are $10000.00 principle, at 5% interest over 5 years.
start_over = 'true'
while start_over == 'true':
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate"))
addition = int(input("Type annual Addition"))
time = int(input("Enter number of years to invest"))
real_rate = rate * 0.01
i = 1
print('total', principle * (1 + real_rate))
while i < time:
principle = (principle + addition) * (1 + real_rate)
i = i + 1
print('total', principle)
for i in range(time):
amount = i * (((1 + rate/100.0) ** time)) * principle
ci = amount - principle
i += 1
print("interest = ",ci)
redo_program = input('To restart type y or to quit type any key ')
if redo_program == 'y':
start_over = 'true'
else:
start_over = 'null'
Here are my outputs:
Type the amount you are investing: 10000
Type interest rate5
Type annual Addition0
Enter number of years to invest5
total 10500.0
total 10500.0
total 11025.0
total 11576.25
total 12155.0625
interest = -12155.0625
interest = 3358.21965978516
interest = 18871.50181957032
interest = 34384.78397935548
interest = 49898.06613914064
To restart type y or to quit type any key
Give this a go:
# Calculate year's values based on inputs and the current value of the account
def calc(current, addition, rate, year):
multiplier = 1 + rate/100 # The interest multiplier
new_total = (current + addition) * multiplier # Calculate the total
interest = round((new_total - current - addition), 2) # Interest to nearest penny/cent
return new_total, interest
def main():
# Inputs
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate: "))
addition = int(input("Type annual Addition: "))
invst_time = int(input("Enter number of years to invest: "))
# Sets current account value to principle
current = principle
# Prints values for each year of investment
for i in range(invst_time):
total, interest_gained = calc(current, addition, rate, i+1)
print("At the end of Year: ", i+1)
print("Total: ", total)
print("Interest: ", interest_gained)
print("------")
current = total # Updates value of account
# Restart Program check
while 1:
repeat_choice = input("Would you like to restart and check with different values? (Y/N)")
if repeat_choice == "Y":
main()
elif repeat_choice == "N":
print("Thanks for using the calculator")
break
else:
print("Enter Y or N!") # Error handler
continue
main()
I have 3 more cars that I have but I need to know how to loop things like the car input so it will allow you to input it again if you do the wrong input same thing with the extras so they have to be either 1 or 0.
print("===================================================")
print("==============Car Finance Calculations=============")
print(" Choose your veicle: ")
print(" SUV type 1 ")
print(" Hatch type 2 ")
print(" Sedan type 3 ")
print("===================================================")
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
if caaaaaaaar == 1:
carsvalue = int(input("Please enter you cars value: "))
residual = carsvalue * 0.30
financing = carsvalue - residual
print(" financing value for the car is: ", round(financing,2))
print(" Intrest rate is 9% ")
n = years * 12
r = 9 / (100 * 12)
Financingcost = financing * ((r*((r+1)**n))/(((r+1)**n)-1))
print(" Your Montly financing rate is: ", round(Financingcost,2))
print("================================================================================")
print("Please Choose extras: ")
print("======================================================")
print(" If you would like fuel type 1 if not type 0")
print(" If you would like insurance type 1 if not type 0")
print(" if you would like Maintenance type 1 if not type 0")
print("======================================================")
if caaaaaaaar == 1:
x, y, z = [int(x) for x in input("Enter Your extras with spaces:").split()]
print("=======================================")
if x == 1:
print("Yes you want fuel")
fuelcost = 80 * 4.33
print("fuel cost is", round(fuelcost,2))
if x == 0:
print("you dont want fuel as an extra")
fuelcost = 0
print("Fuel cost is: ", fuelcost)
print("=======================================")
if y == 1:
print("yes you want insurance")
insurancecost = (1200 / 12)
print("Insurance cost is: ", round(insurancecost,2))
if y ==0:
print("you dont want insurance")
insurancecost = 0
print("insurance cost is: ",insurancecost)
print("=======================================")
if z == 1:
print("yes you want maintenance")
maintenancecost = (100 * 1)
print("Maintenance cost is: ", round(maintenancecost,2))
if z == 0:
print("you dont want maintenance")
maintenancecost = 0
print("maintenance cost is: ",maintenancecost)
print("=======================================")
total_cost_for_extras = fuelcost + maintenancecost + insurancecost
print("Total cost for the selected extras is: ", round(total_cost_for_extras,2))
TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING,2))
You want to use a while loop.
Like this:
carsEntered = 0
while (carsEntered <= 4):
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
carsEntered += 1
You could also use a for loop instead but that depends on what you want to do.
As per my understanding of the question you want to run an iteration until the user gives the right answer.
In that case, you can use flag variable in while.
flag = False
while(flag is False):
if(condition_statisfied):
flag = True
I suggest that you put your vehicle types in a dictionary:
vehicle_type_dict = {
1: "SUV type",
2: "Hatch type",
3: "Sedan type"
}
and do a while-loop to check if your input is in the dictionary:
while True:
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
if caaaaaaaar not in vehicle_type_dict:
continue #loop again if input not in the dictionary
#read next line of code if input is in the dictionary
#do something below if input is correct
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
break #end loop
My recommendation is to take a functional approach to this problem. You are calling int(input()) multiple times and want to validate the user input before proceeding on to the next lines each time. You can do this in a function that will continue to loop until the input is confirmed as valid. Once the input is validated, you can exit the function's frame by returning the value using the return key word.
# This is the function definition.
# The code in this function does not execute until the function is called.
def prompt_int(
text,
minimum=0,
maximum=1,
error="The value you entered is not valid try again."
):
# when the function is called it will start a second while loop that will keep looping
# until valid input is entered
while True:
try:
val = int(input(text))
if minimum <= val <= maximum:
return val
raise ValueError
except ValueError:
print(error)
# This is the outer while loop. It will keep looping forever if the user so chooses.
while True:
# instead of calling print() a bunch one option is to assign a docstring to a variable
car_prompt = '''
===================================================
==============Car Finance Calculations=============
Choose your veicle:
SUV: 1
Hatch: 2
Sedan: 3
===================================================
Please enter the number for the car you want to finance or 0 to exit:\n
'''
# This is where we first call the function.
# Our docstring will be passed into the function to be used as a prompt.
# We also pass in some args for maximum and minimum params
caaaaaaaar = prompt_int(car_prompt, 0, 3)
# 0 is false so we can exit the while loop if the user enters 0
if not caaaaaaaar:
break
year_prompt = "Enter years of the car loan (3, 4 or 5):\n"
years = prompt_int(year_prompt, 3, 5)
if caaaaaaaar == 1:
val_prompt = "Please enter you cars value:\n"
carsvalue = prompt_int(val_prompt, 0, 2147483647)
residual = carsvalue * 0.30
financing = carsvalue - residual
print("Financing value for the car is: ", round(financing, 2))
print("Intrest rate is 9% ")
n = years * 12
r = 9 / (100 * 12)
Financingcost = financing * ((r * ((r + 1) ** n)) / (((r + 1) ** n) - 1))
print(" Your Montly financing rate is: ", round(Financingcost, 2))
print("================================================================================")
print("Please Choose extras: ")
print("======================================================")
x = prompt_int("If you would like fuel type 1 else type 0:\n")
y = prompt_int("If you would like insurance type 1 else type 0:\n")
z = prompt_int("If you would like Maintenance type 1 else type 0:\n")
print("======================================================")
if x == 1:
print("Yes you want fuel")
fuelcost = 80 * 4.33
print("fuel cost is", round(fuelcost, 2))
else:
print("you dont want fuel as an extra")
fuelcost = 0
print("Fuel cost is: ", fuelcost)
print("=======================================")
if y == 1:
print("yes you want insurance")
insurancecost = (1200 / 12)
print("Insurance cost is: ", round(insurancecost, 2))
else:
print("you dont want insurance")
insurancecost = 0
print("insurance cost is: ", insurancecost)
print("=======================================")
if z == 1:
print("yes you want maintenance")
maintenancecost = (100 * 1)
print("Maintenance cost is: ", round(maintenancecost, 2))
else:
print("you dont want maintenance")
maintenancecost = 0
print("maintenance cost is: ", maintenancecost)
print("=======================================")
total_cost_for_extras = fuelcost + maintenancecost + insurancecost
print("Total cost for the selected extras is: ", round(total_cost_for_extras, 2))
TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING, 2))
elif caaaaaaaar == 2:
# Put your code for car 2 in this block.
# If it is like car 1 code except the value of a few variables
# then make another func
pass
else:
# Car 3 code...
pass
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
The purpose is to get the income from the user and apply a set of taxes based on the amount of money the user earns.
income = float(input('Enter your income: $ '))
if income < 35000:
tax_a = float((income * 0.15))
if (income - 35000) < 100000:
tax_b = float((income * 0.25))
if (income - 100000) > 100000:
tax_c = float((income * 0.35))
if income > 50000:
tax_s = (income * 0.05)
fed_tax = float((tax_a + tax_b + tax_c))
total_tax = (fed_tax + tax_s)
print('Your total tax liability is: ${:.2f}'.format(total_tax))
print('[details Federal tax: {:.2f}, State tax: {:.2f}'.format(fed_tax, tax_s))
You are only defining tax_a, tax_b, tax_c and tax_s if some condition is true. If the condition is not true, you leave the variable undefined.
I'm not a tax lawyer, but I assume the tax in a given category is 0 if the condition does not apply:
if income < 35000:
tax_a = float((income * 0.15))
else:
tax_a = 0.0
...and so on.
Need to initialize your variables and learn about "variable scope".
tax_a = tax_b = tax_c = tax_s = 0
income = float(input('Enter your income: $ '))
# ...
$ python incometax.py
Enter your income: $ 100000
Traceback (most recent call last):
File "incometax.py", line 15, in <module>
fed_tax = float((tax_a + tax_b + tax_c))
NameError: name 'tax_a' is not defined
The problem is that tax_a is only defined when a certain condition occurs. Since you always need these variables in the final calculation, you should define them at the beginning of your program:
tax_a = 0.0
p.s. Note that all of the float() calls are unnecessary if you initialize variables with floats to begin with and use floating point constants.
Hello here is my code:
def main():
#Define Variables
HomesSold = [0]
Amount = 0
HomePrice = [0]
Amount = GetAmount(Amount)
HomesSold = AmountHomesSold(Amount)
#print(HomesSold)
def GetAmount (Amount):
global amount
ConvertAmount = float()
ErrorFlag = False
Amount = input("Enter the amount of homes sold this year:")
while not Amount.isdigit():
Amount = input("Please try again, make sure you are entering a positive number (No commas needed): ")
print("The amount of houses sold were: ",Amount)
ConvertAmount = float(Amount)
return ConvertAmount
def AmountHomesSold(HomePrice):
HomePrice = 0
index = 0
while (index < Amount):
HomePrice = GetHomePrice()
HomesSold[index] = HomePrice
index = index + 1
print(HomePrice)
return HomePrice
def GetHomePrice():
HomePrice = input("How much did the homes sell for?")
while not HomePrice.isdigit():
HomePrice = input("Please try again, make sure you are entering a positive number (No commas needed): ")
return HomePrice
main()
So when I try to set my while statement for index < amount, I keep getting an error saying amount is not defined when it is earlier on in my code. Is there a way I can receive that number?
You have to declare "Amount" as a global variable in "AmountHomesSold()" in order to use its value. Otherwise, it will look for a local variable named "Amount" in "AmountHomesSold()" (and there isn't one defined in that function).
Note: I added "global Amount" on the second line to allow the function to use "Amount" as a global variable.
def AmountHomesSold():
global Amount
HomePrice = 0
index = 0
while (index < Amount):
HomePrice = GetHomePrice()
HomesSold[index] = HomePrice
index = index + 1
print(HomePrice)
return HomePrice
For more information, see Use of "global" keyword in Python.