I am just learning python and have my program for Sales Tax running okay but was trying to get my input variables and floating decimal points correct. What would be the correct way to get the decimal place to show the money value with just 2 decimal places.
I have looked through the links and found these helpful links but was still trying to grasp the decimal and cents units better here.
Seems I might have found my answer with this link but will leave the question open for others to learn.
How can I format 2 decimals in Python
Decimals to 2 places for money Python
Two Decimal Places For Money Field
Money and 2 Decimal places.
It seems if I enter 5 as my price, I get 5.300000000000001
I am more familiar with SQL than programming and Python so I'm still learning.
Thanks for your time.
# 01/22/14
# Python Program Sales Tax
#
#Design a program that will ask the user to enter the amount of a purchase.
#The program should then compute the state and county sales tax. Assume the
#state sales tax is 4 percent and the countysalestax is 2 percent. The program
#should display the amount of the purchase, the state sales tax, the county
#sales tax, the total sales tax, and the total of the sale (which is the sum of
#the amount of purchase plus the total sales tax)
#Use the value 0.02, and 0.04
# Display "Enter item_price Amount "
# Input item_price
# Display "state_sales_tax is 4% "
# Set state_sales_tax = 0.04
# Display "county_sales_tax is 2% "
# Set county_sales_tax = 0.02
# print("Your total cost is $",total_price,".",sep="")
county_tax_rate = 0.02
state_tax_rate = 0.04
tax_rate = county_tax_rate + state_tax_rate
item_price = float(input("Please enter the price of your item.\n"))
total_tax_rate = county_tax_rate + state_tax_rate
total_price = item_price * (1 + tax_rate)
print("Your Total Sales Cost is $",total_price,".",sep="")
print("Your Purchase Amount was $",item_price,".",sep="")
print("Your County Tax Rate was $", county_tax_rate,".",sep="")
print("Your State Tax Rate was $", state_tax_rate,".",sep="")
print("Your Total Tax Rate was $", total_tax_rate,".",sep="")
print("Your Total Tax Rate was $", total_tax_rate,".",sep="")
When working with dollar amounts, I would recommend converting everything into cents. So multiply everything (except the tax rates, of course), by 100, then do any arithmetic on it, and finally convert it back to a float. Also, tax_rate and total_tax_rate are equivalent, so just use one. I would change the above to:
county_tax_rate = 0.02
state_tax_rate = 0.04
tax_rate = county_tax_rate + state_tax_rate
item_price = float(input("Please enter the price of your item: "))
item_price = int(100 * item_price) # Item price in cents
total_price = item_price * (1 + tax_rate) # Total price in cents
print("Your Total Sales Cost is ${:0.2f}".format(total_price / 100.0))
print("Your Purchase Amount was ${:0.2f}".format(item_price / 100.0))
print("Your County Tax Rate was {}%".format(int(county_tax_rate * 100)))
print("Your State Tax Rate was {}%".format(int(state_tax_rate * 100)))
print("Your Total Tax Rate was {}%".format(int(tax_rate * 100)))
The {:0.2f} format string takes a float and displays it out to 2 decimal places.
Note: I'm not sure why you were displaying tax rates as dollar amounts, so I changed those to percentages instead.
Related
I need to write a program in Python using def to calculate if it would be profitable to buy a customer card for a discount or not (meaning that the purchase cost after discount + card price is less or equal to the original cost) with the following arguments: total purchase amount in euros,
discount percent with customer card and customer card price. If the card saves the customer some x amount of euros then the function should return x. If purchase + card price is more expensive than the original purchase price then return -x, where x is the number of euros it’s cheaper with the card.
The output should be something like that:
Total purchase amount: 200
Discount percent: 5
Customer card price: 5
It’s better to get a card, you will save 5 euros
So far I manage to write this code but I don't know what to do next:
def customer_card_discount1(total_purchase_amount1, discount_percent1, customer_card_price1):
new_price = (total_purchase amount1) * (100 - discount_percent1)/100 +
(customer_card_price1)
if new_price <= total_purchase amount1:
return customer_card_price1 - new_price
elif new_price > total_purchase amount1:
return customer_card_price1 - new_price
try:
total_purchase_amount1 - int(input("Total purchase amount"))
discount_percent1 - int(input("Discount percent"))
customer_card_price1 - int(input("Customer card price"))
You may have overthought this. If I understood it correctly, all you need is to compare the original price (without any discounts) with the new price (original price, plus card price minus customer discount). This leads to a much simpler solution:
def customer_card_discount1(total_purchase_amount1, discount_percent1, customer_card_price1):
new_price = (total_purchase_amount1) * (100 - discount_percent1)/100 + customer_card_price1
return total_purchase_amount1 - new_price
total_purchase_amount1 = int(input("Total purchase amount: "))
discount_percent1 = int(input("Discount percent: "))
customer_card_price1 = int(input("Customer card price: "))
print(customer_card_discount1(total_purchase_amount1, discount_percent1, customer_card_price1))
Example
Input: 200 / 5 / 5 -> Output: 5
Input: 200 / 5 / 15 -> Output: -5 (customer card costs more)
If I understood your question correctly, the following simple code should suffice:
def customer_card_discount1(total_purchase_amount1, discount_percent1, customer_card_price1):
new_price = (total_purchase_amount1) * (100 - discount_percent1)/100 + (customer_card_price1)
if new_price <= total_purchase_amount1:
return ("You save {savings} euro, you should purchase a customer card,".format(savings=total_purchase_amount1 - new_price))
else:
return ("Don't buy a card, it would cost you {cost} euro more.".format(cost=total_purchase_amount1 - new_price))
A few comments:
It may have been a typo at the time of writing your question on StackOverflow, but in your code, the total_purchase amount1 variable is missing an underscore, which would throw an error. It should be total_purchase_amount1.
Inside the if-statements, you are returning the difference between customer_card_price1 and new_price, which's not really what you're looking for? You want to compare the total purchase price with the new price.
Also, the next time you post on StackOverflow, try to include any errors that you're getting or to explain in more details what is it exactly that you're stuck on.
def profit(total_purchase,discount_percent,card_price):
discount=discount_percent / 100 * total_purchase
newpurchase= total_purchase - discount + card_price
netamount=total_purchase-newpurchase
# if netamount>0 then there would be benefit in buying card
if netamount>0:
print("Profit")
return netamount
# if netamount<=0 then there would be no benefit in buying card
print("Loss")
return netamount
print(profit(200,5,20))
Loss
Output is -10.0
# Write your solution here
times = int(input("How many times a week do you eat at the student cafeteria? "))
price = float(input("The price of a typical student lunch? "))
groc = float(input("How much money do you spend on groceries in a week? "))
print("Average food expenditure:")
print (f"Daily: {times * price + groc / 7} ")
puts out:
How many times a week do you eat at the student cafeteria? 4
The price of a typical student lunch? 2.5
How much money do you spend on groceries in a week? 28.5
Average food expenditure:
Daily: 14.071428571428571 I need it to be 5.5 not 14.07
Pls can anyone help out must be piece of cake for a pro XD
also need weekly output of 38.5. but i dont know what im doing wrong i think i must prioritize the math but idk how to do it.
You have a precedence problem.
In arithmetic expressions, multiplication and division happen before addition. So this:
times * price + groc / 7
divides groc by 7 and then adds it to the result of multiplying times by price. You want instead to divide the whole value tiems * price + groc by 7, which means you need parentheses:
(times * price + groc) / 7
Well, for the daily output just use parentheses.
Like simple math, ((times*price)+groc)/7
and I'm pretty sure this will do.
As for the weekly if I'm getting this right, just do this,
weekly = (daily * 7)
again, if you are doing this directly use parentheses.
cafeteria = float(input("How many times a week do you eat at the student ""
cafeteria? "))
price = float(input("The price of a typical student lunch? "))
money = float(input("How much money do you spend on groceries in a week? "))
spent = money + (cafeteria * price)
print("Average food expenditure:\n")
print("Daily:", spent / 7, "euros")
print("Weekly:", spent, "euros")
this was my solution in that course.
I just picked up coding for the first time and started with the MIT free intro to python course. I am on the first problem of the second homework and I am having a hard time figuring out how to solve. I saw some other posts about this but I think it would be way easier to learn if someone could show me how to do it with my code rather than anothers.
This is the problem:
You have graduated from MIT and now have a great job! You move to the
San Francisco Bay Area and decide that you want to start saving to buy
a house. As housing prices are very high in the Bay Area, you realize
you are going to have to save for several years before you can afford
to make the down payment on a house. In Part A, we are going to
determine how long it will take you to save enough money to make the
down payment given the following assumptions:
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.
Here is my code so far:
total_cost = float(input("What is the cost of the home? "))
annual_salary = float(input("What is your annual salary? "))
portion_saved = float(input("How much would you like to save per year? "))
portion_down = (total_cost*.25)
current_savings = 0
monthly_salary = (annual_salary/12)
interest_rate = .04
#goal is to loop up until I have enough for the down payment
print (total_cost)
print (annual_salary)
print (portion_saved)
print ("The downpayment required for this house is", portion_down)
#need to use +=, otherwise you would have to do current saving = current savings + 1
months = 1
while current_savings < portion_down:
current_savings += current_savings*(.4/12) #monthly interest
current_savings += portion_saved #monthly savings
months += months + 1
print ("It will take", months, "months to save the needed down payment of", portion_down)
You did a pretty good job.
The biggest problem I see in your code is:
months += months + 1
You need to change it to:
months +=1
I also made some tweaks in your code, but essentially I kept the same idea:
total_cost = float(input("What is the cost of the home? "))
monthly_salary = float(input("What is your monthly salary? "))
#portion_saved = float(input("How much would you like to save per year? "))
portion_down = (total_cost*.25)
current_savings = 0
interest_rate = 0.04
months = 1
portion_saved = 0.1
print ("The downpayment required for this house is", portion_down)
while current_savings < portion_down:
current_savings += current_savings(interest_rate/12)+portion_saved*monthly_salary
months +=1
print ("It will take", months, "months to save the needed down payment of",portion_down)
This is my code and I want to save the output of this program into the text file.
#Compound Interest Calculation
#The formula for annual compound interest, including principal sum, is:
"""A = P*(1 + r/n)**(nt)
Where:
A = the future value of the investment/loan, including interest
P = the principal investment amount (the initial deposit or loan amount)
r = the annual interest rate (decimal)
n = the number of times that interest is compounded per year
t = the number of years the money is invested or borrowed for"""
# File Objects
with open('py.data.txt','w') as file: #in write mode
file.write(str(cName))
cName = int(input("Enter the customer name:"))
print("The cutomer name is" , cName)
date_entry = int(input("Enter a date in YYYY-MM-DD format:"))
print("The investment date is" , date_entry)
P = float(input("Please enter the amount you would like to invest:"))
print("The interest rate varies with the number of years")
t = float(input("please enter the number of years the money is inested or borrowed for:"))
print("The interest rate varies with the number of years")
if (t>=10):
r = 0.05
print("interest rate=0.05")
elif (t>=5):
r = 0.03
print("interest rate=0.03")
else:
r = 0.02
print("interest rate=0.02")
n = float(input("Please enter the number of times that interest is compounded per year:"))
A = P*(1 + r/n)**(n*t)
print("The value of investment is £" , A)
If you simply want to save the print statement in another txt file you may run the python code with like this:
python file.py > output.txt
This will save the console output in output.txt in the directory where your code is running
cName = int(input("Enter the customer name:"))
print("The cutomer name is" , cName)
date_entry = int(input("Enter a date in YYYY-MM-DD format:"))
print("The investment date is" , date_entry)
P = float(input("Please enter the amount you would like to invest:"))
print("The interest rate varies with the number of years")
t = float(input("please enter the number of years the money is inested or borrowed for:"))
print("The interest rate varies with the number of years")
if (t>=10):
r = 0.05
print("interest rate=0.05")
elif (t>=5):
r = 0.03
print("interest rate=0.03")
else:
r = 0.02
print("interest rate=0.02")
n = float(input("Please enter the number of times that interest is compounded per year:"))
A = P*(1 + r/n)**(n*t)
print("The value of investment is £" , A)
**PyData = open('py.data.txt','w') as file: #in write mode
PyData.write(cName,date_entry,P,t,A ) #Data type is irrelevant... I don't know if it is a comata or a plus
PyData.close()**
The last part is from a project of mine so it should work, and also you referenced cName before it was assigned.
Kind Regards
I am new to Python and assistance is needed with the following exercise:
Exercise 3.1 The cover price of a book is $24.95, but bookstores get a 40 percent discount.Shipping costs $3 for the first copy and 75 cents for each additional copy. Calculate the total wholesale costs for 60 copies.
I am trying to figure out code that gives you the total discounted price along with shipping fees based off of the input.
book = 14.97
print("How many books", end='')
print (float (input()) * book + (.75 * 59 )+3)
You must clarify your question, and ask for code not for solution of a problem.
You probably have to define function to do the calculation:
def cost(num_of_books):
book_price = 14.97
discount = 0.4
# Price without shipping
price = book_price * (1-discount) * num_of_books
# Adding shipping
total_price = price + 0.75*(num_of_books -1) + 3
return total_price