Sales tax calculator with a while loop - python

I am making a sales tax calculator and everything works besides the total payment amount portion. In my program I want to be able to input a number and get the taxed amount on the item I also want to be able to get the total amount payed including tax in the transaction. The code I have written so far does all of that but when I input a second number I want that numbers total payment to be added to the previous total payment. for example if you input 3.99 it gives you a total payment of 4.3441125000000005 then if you input 12.95 it should give you a total payment of 18.443425 because 12.95's total payment is 14.0993125 + 4.3441125000000005.
rate = 0.08875 #sales tax
amount = 1
while amount != 0:
amount = float(input("Enter item cost in dollars, 0 to quit: ")) #cost of item
tax = amount*rate #tax amount on item
total = amount+tax #total payment including tax
print("Tax amount on this item ==", tax)
print("Total payment ==", total)
so I basically just want the totals to add each time you input a cost.

You could create a new variable:
rate = 0.08875 #sales tax
amount = 1
full_total = 0
while amount != 0:
amount = float(input("Enter item cost in dollars, 0 to quit: ")) #cost of item
tax = amount*rate #tax amount on item
total = amount+tax #total payment including tax
full_total += total
print("Tax amount on this item ==", tax)
print("Total payment ==", total)
print(f"Your full total today is {full_total}")

Related

Unsure why output is 0. Trying to count months to pay downpayment

print("Please enter you starting annual salary: ")
annual_salary = float(input())
monthly_salary = annual_salary/12
print("Please enter your portion of salary to be saved: ")
portion_saved = float(input())
print ("Please enter the cost of your dream home: ")
total_cost = float(input())
current_savings = 0
r = 0.04/12
n = 0
portion_down_payment = total_cost*int(.25)
if current_savings < portion_down_payment:
monthly_savings = monthly_salary*portion_saved
interest = monthly_savings*r
current_savings = current_savings + monthly_savings + interest
n =+ 1
else:
print(n)
The above is my code. I keep getting output = 0 but unsure why.
This the problem statement, I am a HS student attempting OCW coursework.
Call the cost of your dream home ​total_cost​.
Call the portion of the cost needed for a down payment ​portion_down_payment​. For simplicity, assume that portion_down_payment = 0.25 (25%).
Call the amount that you have saved thus far ​current_savings​. You start with a current savings of $0.
Assume that you invest your current savings wisely, with an annual return of ​r ​(in other words, at the end of each month, you receive an additional ​current_savings*r/12​ funds to put into your savings – the 12 is because ​r​ is an annual rate). Assume that your investments earn a return of r = 0.04 (4%).
Assume your annual salary is ​annual_salary​.
Assume you are going to dedicate a certain amount of your salary each month to saving for the down payment. Call that ​portion_saved​. This variable should be in decimal form (i.e. 0.1 for 10%).
At the end of each month, your savings will be increased by the return on your investment, plus a percentage of your ​monthly salary ​(annual salary / 12). Write a program to calculate how many months it will take you to save up enough money for a down payment. You will want your main variables to be floats, so you should cast user inputs to floats.
Your program should ask the user to enter the following variables:
The starting annual salary (annual_salary)
The portion of salary to be saved (portion_saved)
The cost of your dream home (total_cost)
Test Case 1
Enter your annual salary:​ 120000 Enter the percent of your salary to save, as a decimal:​ .10 Enter the cost of your dream home:​ 1000000 Number of months:​ 183
You have n =+ 1 but I think you mean n += 1
Also int(.25) evaluates to 0, I think you want int(total_cost*.25). As your code is, the if statement will always evaluate to False because current_savings == 0 and portion_down_payment == 0
More generally, when your code isn't working as expected, you should put in either print() or assert statements to narrow down where your code is deviating from what you expect. For example, before the if statement you could have it print the two values you are comparing.

How to use format()?

My teacher gave me this assigment"Write a program that calculates the bill of sale for three items purchased. The cost of each item will be read from the user and stored into variables. The receipt will show the number of items purchased, the cost of each item, the average cost per item, the tax rate (.0825% in Texas), the tax amount, and the total cost" I'was able to do it with basic input and variables but i had some trouble when he asked me to use format() in the code because there's always a different error. Here's my attempt.
cost_1 = float(input("Enter cost of item 1:"))
cost_2 = float(input("Enter cost of item 2:"))
cost_3 = float(input("Enter cost of item 3:"))
cost = ['cost_1', 'cost_2', 'cost_3']
sentence = 'Cost 1: {0} Cost 2: {1} Cost 3: {2}'.format(cost, float['cost_1'], cost, float['cost_2'], cost, float['cost_3'])
print(sentence)
Average_cost = float(cost_1 + cost_2 + cost_3)/3
Total_cost = float(cost_1 + cost_2 + cost_3)
print("Average cost:", Average_cost)
print("Total cost:", Total_cost)
Tax_rate = float(8.25)
print("Tax rate:", Tax_rate)
Taxes = float(Total_cost*Tax_rate/100)
print ("Taxes:",float(Taxes))
Total = Total_cost + Taxes
print("Total:", Total)
I will not give you the answer, but I will explain a couple things you are doing wrong.
cost_1 = float(input("Enter cost of item 1:"))
cost_2 = float(input("Enter cost of item 2:"))
cost_3 = float(input("Enter cost of item 3:"))
# below you are assigning strings to the cost array, you should not have quotes here
cost = ['cost_1', 'cost_2', 'cost_3']
# below you are trying to format with three variables but are passing four.
# you are also trying to access the float function as a dict type.
sentence = 'Cost 1: {0} Cost 2: {1} Cost 3: {2}'.format(cost, float['cost_1'],
cost, float['cost_2'], cost, float['cost_3'])
print(sentence)
# there is no need to constantly float variables that are float
Average_cost = float(cost_1 + cost_2 + cost_3)/3
# agagin
Total_cost = float(cost_1 + cost_2 + cost_3)
print("Average cost:", Average_cost)
print("Total cost:", Total_cost)
# a float number is already a float, you dont need to declare it as float
Tax_rate = float(8.25)
print("Tax rate:", Tax_rate)
Taxes = float(Total_cost*Tax_rate/100)
print ("Taxes:",float(Taxes))
Total = Total_cost + Taxes
print("Total:", Total)
I will give you a little help with the cost list.
items_count = 3
cost = []
for i in range(items_count):
cost.append(float(input("enter price for item %d: " % (i+1))))
Also, there is a function called sum that will add up all the numbers in a list. Here is a tutorial https://www.programiz.com/python-programming/methods/built-in/sum

Calculation error at runtime in python loan calculator

I'm trying to build a loan calculator that takes in the amount owed and interest rate per month and the down payment put at the beginning and the monthly installments so it can output how many months do you need to pay off your debt. The program works just fine when I enter an interest_rate below 10% but if I type any number for example 18% it just freezes and gives no output. When I stop running the program it gives me these errors:
Traceback (most recent call last):
File "C:\Users\Khaled\PycharmProjects\interest_payment\main.py", line 35, in <module>
months_to_finish = get_months(price) # this returns the number of months from the counter var
File "C:\Users\Khaled\PycharmProjects\interest_payment\main.py", line 6, in get_months
price = price - installments
KeyboardInterrupt
This is my code:
def get_months(price):
counter = 0
price = price - down_payment
while price > 0:
price = price + price * interest_rate
price = price - installments
counter += 1
return counter
if __name__ == '__main__':
price = float(input("Enter price here: "))
interest_rate = float(input("Enter interest rate here: %")) / 100
while interest_rate < 0:
interest_rate = float(input('Invalid interest rate please try again: %')) / 100
down_payment = int(input("Enter your down payment here: $"))
while down_payment > price or down_payment < 0:
down_payment = int(input('Invalid down payment please try again: $'))
choice = input("Decision based on Installments (i) or Months to finish (m), please write i or m: ").lower()
if choice == 'm':
print('m')
elif choice == 'i':
installments = int(input("What's your monthly installment budget: ")) # get the installments
months_to_finish = get_months(price) # this returns the number of months from the counter var
print(f"It will take {months_to_finish} months to finish your purchase.")
else:
print('Invalid choice program ended')
These are the test values:
Enter price here: 22500
Enter interest rate here: %18
Enter your down payment here: $0
Decision based on Installments (i) or Months to finish (m), please write i or m: i
What's your monthly installment budget: 3000
With an initial principal of $22,500, an interest rate of 18%, a down payment of $0, and a monthly payment of $3,000, it will take an infinite number of months to pay off the loan. After one period at 18% interest, you have accrued $4,050 of interest. Since you're only paying $3,000 per period, you're not even covering the amount of new interest, and the total amount you owe will grow forever. You probably want to check somewhere that the monthly payment is greater than the first month's interest. You could modify your code like this:
if installments < (price - down_payment) * interest_rate:
print("The purchase cannot be made with these amounts.")
else:
months_to_finish = get_months(price)
print(f"It will take {months_to_finish} months to finish your purchase.")
l=[]
n=int(input())
i=0
for i in range(n):
l.append(str(input()))
def long(x):
if x>10:
return print(l[i][0]+str(len(l[i])-2)+l[i][-1])
def short(x):
if x<=10:
return print(l[i])
i=0
for i in range(len(l[i])):
long(len(l[i]))
short(len(l[i]))
continue

How to work out the percentage of an inputted number?

I've started using python a few days ago and am having difficulty in adding 20% (VAT) of the answer to 'Enter the total cost of the meal'. So, say the user inputted 80, how would I get it to add 20% of the inputted answer (80) to the total cost? Thank you in advance!
quotient = 1 / 5
percentage = quotient * 100
total_cost = float(input('Enter the total cost of the meal: '))
total_cost_vat=total_cost+percentage
print("Total cost of meal inclusive of VAT is",total_cost_vat)
number_of_people = float(input('Enter the number of people paying: '))
var1 = float(input(total_cost_vat / number_of_people))
You first create a variable quotient and you make it equal 1/5 or 0.2.
But now you times it by 100? Why? And then instead of multiplying total_cost_vat you add basically 20 to it. Why?
vat_percentage = 0.2 # In math 0.2 is 20%
subtotal_cost = float(input('Enter the total cost of the meal: '))
# Add 1 to the percentage to get total + vat
total_cost = subtotal_cost * (1 + vat_percentage)
If you know for sure that the tax is going to be 20% every time you calculate the VAT you can just multiply the total cost by 1.2, otherwise you can have the tax as a variable in decimal form. Then you multiply the pre tax cost by 1 + the tax.
tax = 0.20
pre_tax = float(input('Enter the total cost of the meal: '))
total_cost_vat = pre_tax * (1 + tax)
print("Total cost of meal inclusive of VAT is",total_cost_vat)
number_of_people = float(input('Enter the number of people paying: '))
print(total_cost_vat / number_of_people)
I coded it up below and annotated it. Some of the code you had wasn't necessary.
If you don't know that it is always going to be 20% you can use the below code and change the value of the variable:
# step 1: simpler than 1/5
percentage = 0.2
# step 2: getting input
total_cost = float(input('Enter the total cost of the meal: '))
# step 3: calculating the cost with the vat
total_cost_vat = total_cost + (percentage * total_cost)
# step 4: printing our value
print(total_cost_vat) # printing vat value
If you do know the value of the vat you can replace step 3 with below code:
total_cost_vat = 1.2 * total_cost
Hope this helped!

Python assign variable names to if else function

# Determine price per pound
if quantity >= 40:
print('Cost of coffee $', format(quantity * 7.50,'.2f'),sep='')
else:
if quantity >= 20:
print ('Cost of coffee $', format(quantity * 8.75, '.2f'), sep='')
else:
if quantity >= 10:
print ('Cost of coffee $', format (quantity * 10.00, '.2f'), sep='')
else:
if quantity >= 1 or quantity <= 9:
print ('Cost of coffee $', format (quantity * 12.00, '.2f'), sep='')
Im trying to figure out how I get the total (cost per pound * quantity entered) assigned to a variable. I need to be able to take the total before tax and multiple it by 7% tax. Above is the formula I have to find out how much it will cost based on the quantity and price.
So you'll need to use another variable to keep track of the total cost, for this I'll use total. Then we can set that equal to quantity * price using the flow controls. For this you'll want to look further into using if, elif, else.
After that you can use the total to calculate the tax, which is pretty straight forward.
Finally you can use the same print statement you had in each if statement to output the total cost.
# initialize a variable to keep track of the total
total = 0
# Determine price per pound
# use if elif
if quantity >= 40:
total = quantity * 7.50
elif quantity >= 20:
total = quantity * 8.75
elif quantity >= 10:
total = quantity * 10.00
else:
total = quantity * 12.00
# do the tax calculations using total
total = total * 1.07
# print the result
print('Cost of coffee $', format(total,'.2f'), sep='')
If you want to calculate and use the tax separately, you'll need to use another variable. Just like the example above used total. This time we'll add a variable called tax.
Then we'll add another print statement to output it.
# initialize a variable to keep track of the total
total = 0
# Determine price per pound
# use if elif
if quantity >= 40:
total = quantity * 7.50
elif quantity >= 20:
total = quantity * 8.75
elif quantity >= 10:
total = quantity * 10.00
else:
total = quantity * 12.00
# do the tax calculations assigning it to a different variable
tax = total * 0.07
# add the tax to the total
total = total + tax
# print the tax
print('Tax $', format(tax,'.2f'), sep='')
# print the total
print('Cost of coffee $', format(total,'.2f'), sep='')

Categories