I am currently trying to create a code that will calculate the discount (in percentage) of a product.
The code is supposed to ask the user of the code for the original price of the code, the discounted price, then it should tell the user what the discount was (in percentage). But it is not showing the correct percentage right now.
Here is the code so far:
o = float(input('The original ticket price: $'))
d = float(input('The price after the discount: $'))
p = 100/(o/d)
p2 = str(round(p, 2))
print('The discount (in percentage) is', p2,'%')
The calculations that you put in your code are incorrect.
Here's an improved version that I whipped up, and I hope this helps you:
if option == 3:
o = float(input('The ticket (original) price($): '))
dp = float(input('Price after the discount($): '))
p = 100/(o/dp)
d = str(round(100 - p, 2))
print('The percentage discount is', d,'%')
The formula you are using is not correct, try this:
o = float(input('The original ticket price: $'))
d = float(input('The price after the discount: $'))
p = (1 - d / o) * 100
p2 = str(round(p, 2))
print('The discount (in percentage) is', p2,'%')
Just did something similar to this myself. Here's the code I used:
It's essentially using the following formula to work out the amount saved, then deducts it from the main cost:
Total = cost * sunflower
Discount = Total * 0.1
FinalCost = Total - Discount
An actual functional piece of code would look like:
# $5.00 Sunflowers at 10% off calculator:
#variables
cost = 5
Sunflowers = 10
#calculator
Total = float(cost) * int(Sunflowers)
Discount = float(Total) * 0.1
FinalCost = float(Total) - float(Discount)
print("Final price of: ", Sunflowers , ": $", FinalCost)
Related
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
I want my output to have a 2 decimal places result. What should I do?
Ideal output is:
Enter the number of plants to purchase: 14
Enter the price per unit of plant: 250.00
The total payable amount is: P3,350.00
n1 = input('Enter number of plants: ')
n2= input('Enter price per unit: ')
mul= float(n1) * float(n2)
mul2= (float(n1)-float(10)) * (float(n2))
mul3 = float(10) * float(n2)
discount2 = float (mul2)* float(0.15)
total2=mul2-discount2
total3= total2+mul3
if float(n1)<=float(10):
mul= float(n1) * float(n2)
print('The total payable amount is: ', mul)
elif float(n1)>float(10):
print('The total payable amount is: ', total3)
A few answers missed the fact you also needed thousands separated by a comma. here is the format command which displays the price the way you expect it
n1 = input('Enter number of plants: ')
n2= input('Enter price per unit: ')
mul= float(n1) * float(n2)
mul2= (float(n1)-float(10)) * (float(n2))
mul3 = float(10) * float(n2)
discount2 = float (mul2)* float(0.15)
total2=mul2-discount2
total3= total2+mul3
if float(n1)<=float(10):
mul= float(n1) * float(n2)
print('The total payable amount is: ${:0,.2f}'.format(mul))
elif float(n1)>float(10):
print('The total payable amount is: ${:0,.2f}'.format(total3))
Use a formatted string. Also, convert the values to floats at the start, then there is no need to keep converting everything.
plants_str = input('Enter number of plants: ')
price_str = input('Enter price per unit: ')
plants = float(plants_str)
price = float(price_str)
total = plants * price
if plants > 10:
total -= 0.15 * (plants - 10) * price
print(f"The total payable amount is: {total:0,.2f}")
But as noted in a comment, for serious applications involving currency you should use the decimal library. This ensures decimal numbers are represented exactly.
from decimal import Decimal
plants_str = input('Enter number of plants: ')
price_str = input('Enter price per unit: ')
plants = Decimal(plants_str)
price = Decimal(price_str)
total = plants * price
if plants > 10:
total -= Decimal("0.15") * (plants - 10) * price
print(f"The total payable amount is: {total:0,.2f}")
You can use the str.format function and I made some small adjustments to your code.
n1 = float(input('Enter number of plants: '))
n2 = float(input('Enter price per unit: '))
mul = n1 * n2
if n1<=10:
print('The total payable amount is: ${:0,.2f}'.format(mul))
else:
print('The total payable amount is: ${:0,.2f}'.format(0.85*mul+1.5*n2))
Can anyone help me writing the split_check() function?.
The problem statement is:
Write a split_check function that returns the amount that each diner
must pay to cover the cost of the meal. The function has 4 parameters:
bill: The amount of the bill. people: The number of diners to split
the bill between. tax_percentage: The extra tax percentage to add to
the bill. tip_percentage: The extra tip percentage to add to the bill.
The tax or tip percentages are optional and may not be given when
calling split_check. Use default parameter values of 0.15 (15%) for
tip_percentage, and 0.09 (9%) for tax_percentage
I need to calculate the amount of tip and tax, add to the bill total, then divide by the number of diners.
bill = float(input())
people = int(input())
#Cost per diner at the default tax and tip percentages
print('Cost per diner:', split_check(bill, people))
bill = float(input())
people = int(input())
new_tax_percentage = float(input())
new_tip_percentage = float(input())
# Cost per diner at different tax and tip percentages
print('Cost per diner:', split_check(bill, people, new_tax_percentage, new_tip_percentage))
You can see only bill and people are required, so you should add default values to your arguments:
def split_check(bill, people, tax = 0.09, tip = 0.15)
That means that if only two arguments are given, like in the first case, the tax and tip percentages will be 9% and 15% respectively. You should add to bill the amount bill*tax and bill*tip. In the end, you'll divide the bill by the number of people and return it.
So we have this:
def split_check(bill, people, tax = 0.09, tip = 0.15):
taxes = bill * tax
tips = bill * tip
return (bill + taxes + tips) / people
You can also check if people is not smaller or equal to 0, if the arguments are numbers and not strings for example, and if tax and tip are between 0 and 1, etc. using a try/except block.
Heres what I did:
I named the parameters with all default amounts
named new local variables to get new amounts
returned the per_person calculation
def split_check(bill=0, people=0, tax_percentage=0.09, tip_percentage=0.15):
new_check = (bill * tax_percentage) + bill
new_tip = bill * tip_percentage
per_person = (new_check + new_tip) / people
return per_person
bill = float(input())
people = int(input())
# Cost per diner at the default tax and tip percentages
print('Cost per diner:', split_check(bill, people))
bill = float(input())
people = int(input())
new_tax_percentage = float(input())
new_tip_percentage = float(input())
# Cost per diner at different tax and tip percentages
print('Cost per diner:', split_check(bill, people, new_tax_percentage, new_tip_percentage))
this works for me
def split_check(bill=0.0, people=0, tax_percentage=0.09, tip_percentage=0.15):
bill_per_diner = ((bill + ((tax_percentage * bill) + (tip_percentage * bill))) / people)
return bill_per_diner
Taking all of the comments into account to understand the problem completely, here's an answer that produces the right result:
def split_check(bill, people, tax = 0.15, tip = 0.09):
tax = bill * tax
tip = bill * tip
return (bill + tax + tip)/people
print('Cost per diner:', split_check(25, 2))
Or more concisely:
def split_check(bill, people, tax = 0.15, tip = 0.09):
return bill * (1.0 + tax + tip) / people
print('Cost per diner:', split_check(25, 2))
Result:
Cost per diner: 15.5
# 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='')
I am currently learning python through a video tutorial on youtube, and have come up against a formula I cannot seem to grasp, as nothing looks right to me. The basic concept of the excersise is to make a mortgage calculator that asks the user to input 3 pieces of information, Loan Amount, Interest Rate, and Loan Term (years)
then it calculates the monthly payments to the user. here is my code:
__author__ = 'Rick'
# This program calculates monthly repayments on an interest rate loan/mortgage.
loanAmount = input("How much do you want to borrow? \n")
interestRate = input("What is the interest rate on your loan? \n")
repaymentLength = input("How many years to repay your loan? \n")
#converting the string input variables to float
loanAmount = float(loanAmount)
interestRate = float(interestRate)
repaymentLength = float(repaymentLength)
#working out the interest rate to a decimal number
interestCalculation = interestRate / 100
print(interestRate)
print(interestCalculation)
#working out the number of payments over the course of the loan period.
numberOfPayments = repaymentLength*12
#Formula
#M = L[i(1+i)n] / [(1+i)n-1]
# * M = Monthly Payment (what were trying to find out)
# * L = Loan Amount (loanAmount)
# * I = Interest Rate (for an interest rate of 5%, i = 0.05 (interestCalculation)
# * N = Number of Payments (repaymentLength)
monthlyRepaymentCost = loanAmount * interestCalculation * (1+interestCalculation) * numberOfPayments / ((1+interestCalculation) * numberOfPayments - 1)
#THIS IS FROM ANOTHER BIT OF CODE THAT IS SUPPOSE TO BE RIGHT BUT ISNT---
# repaymentCost = loanAmount * interestRate * (1+ interestRate) * numberOfPayments / ((1 + interestRate) * numberOfPayments -1)
#working out the total cost of the repayment over the full term of the loan
totalCharge = (monthlyRepaymentCost * numberOfPayments) - loanAmount
print("You want to borrow £" + str(loanAmount) + " over " + str(repaymentLength) + " years, with an interest rate of " + str(interestRate) + "%!")
print("Your monthly repayment will be £" + str(monthlyRepaymentCost))
print("Your monthly repayment will be £%.2f " % monthlyRepaymentCost)
print("The total charge on this loan will be £%.2f !" % totalCharge)
Everything works, but the value it throws out at the end is completely wrong... a £100 loan with an interest rate of 10% over 1 year shouldn't be making me pay £0.83 per month. Any help in getting my head around this equation to help me understand would be greatly appreciated.
With the help of examples, this is what I did.
# Formula for mortgage calculator
# M = L(I(1 + I)**N) / ((1 + I)**N - 1)
# M = Monthly Payment, L = Loan, I = Interest, N = Number of payments, ** = exponent
# Declares and asks for user to input loan amount. Then converts to float
loanAmount = input('Enter loan amount \n')
loanAmount = float(loanAmount)
# Declares and asks user to input number of payments in years. Then converts to float. Years * 12 to get
# total number of months
years = input('How many years will you have the loan? \n')
years = float(years) * 12
# Declares and asks user to input interest rate. Then converts to float and input interest rate is /100/12
interestRate = input('Enter Interest Rate \n')
interestRate = float(interestRate) / 100 / 12
# Formula to calculate monthly payments
mortgagePayment = loanAmount * (interestRate * (1 + interestRate)
** years) / ((1 + interestRate) ** years - 1)
# Prints monthly payment on next line and reformat the string to a float using 2 decimal places
print("The monthly mortgage payment is\n (%.2f) " % mortgagePayment)
This mortgage package does it nicely:
>>> import mortgage
>>> m=mortgage.Mortgage(interest=0.0375, amount=350000, months=360)
>>> mortgage.print_summary(m)
Rate: 0.037500
Month Growth: 1.003125
APY: 0.038151
Payoff Years: 30
Payoff Months: 360
Amount: 350000.00
Monthly Payment: 1620.91
Annual Payment: 19450.92
Total Payout: 583527.60
I also watched this youtube video and had the same problem.
I'm a python newbie so bear with me.
The instructors in the video were using python3 and I am using python2
so I am not sure if all the syntax are the same. But using some information found in this thread and info from this link: (http://www.wikihow.com/Calculate-Mortgage-Payments) I was able to get the answer. (My calculations matched an online mortgage calculator)
#!/usr/bin/env python
# The formula I used:
M = L * ((I * ((1+I) ** n)) / ((1+I) ** n - 1))
# My code (probably not very eloquent but it worked)
# monthly payment
M = None
# loan_amount
L = None
# interest rate
I = None
# number of payments
n = None
L = raw_input("Enter loan amount: ")
L = float(L)
print(L)
I = raw_input("Enter interest rate: ")
I = float(I)/100/12
print(I)
n = raw_input("Enter number of payments: ")
n = float(n)
print(n)
M = L * ((I * ((1+I) ** n)) / ((1+I) ** n - 1))
M = str(M)
print("\n")
print("Monthly payment is " + M)
Apparently you copied the formula wrong.
wrong: * numberOfPayments
correct: ** numberOfPayments
note: it appears twice in the formula
note: in python, ** is "to the power of" operator.
This worked pretty well for me. Not exact, as loan calculators usually go by days, and I'm lazy so I go by months but here's a simple one I wrote that is accurate enough to be practical.
L = input("How much will you be borrowing? ")
L = float(L)
print(L)
N = input("How many years will you be paying this loan off? ")
N = float(N) *12
print(N)
I = input("What is the interest in percents that you will be paying? Ex, 10% = 10, 5% = 5, etc. ")
I = float(I)/100
print(I)
M = (L/N) + I*(L/N)
float(M)
print("Your monthly payment will be: ")
print(M)
I also came accross this problem and this is my solution
loan = input('Enter Loan Amount: ')
loan = float(loan)
numberOfPayments = input('Enter Loan payments in years: ')
numberOfPayments = float(numberOfPayments) * 12
interest = input('Annuel interest Rate: ')
interest = float(interest)/100/12
monthlyPayments = loan * (interest * (1 + interest) ** numberOfPayments) / ((1 + interest) ** numberOfPayments - 1)
print (round(monthlyPayments))