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
Related
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)
I'm trying to create a function that is essentially a buy back program with bottles, the rules are as follows
money -> the amount of money the customer has
bottlesOwned -> the number of bottles the customer has to exchange
price -> the price of a bottle of soda pop
exchangeRate -> the exchange rate, expressed as a tuple. the first element is the minimum size of the group of bottles that can be exchanged. The second argument is the refund received for one group of bottles.
A customer may refund as many groups of bottles as they like on a single visit to the store, but the total number of bottles refunded must be a multiple of the first element of exchangeRate.
The function must output the total number of bottles which the customer is able to purchase over all trips, until the customer runs out of money.
def lightningBottle(money, bottlesOwned, price, exchangeRate):
if bottlesOwned >= exchangeRate[0]:
bottlesOwned -= exchangeRate[0]
money += exchangeRate[1]
if money >= price:
bottlesOwned += 1
bottlesbought += 1
money -= price
return lightningBottle(money, bottlesOwned, price, exchangeRate)
else:
print ("we bought",bottlesbought,"bottles")
return bottlesbought
this is as far as I've gotten but I cannot figure out how to get the bottlesbought counter to tick up without using a global variable (I can't use a global because it does not reset on concurrent tests and provides the wrong answer)
You're close. You just need bottlesbought to be an argument of your function:
def lightningBottle(money, bottlesOwned, price, exchangeRate, bottlesbought=0):
if bottlesOwned >= exchangeRate[0]:
bottlesOwned -= exchangeRate[0]
money += exchangeRate[1]
if money >= price:
bottlesOwned += 1
bottlesbought += 1
money -= price
return lightningBottle(money, bottlesOwned, price, exchangeRate, bottlesbought)
else:
print ("we bought",bottlesbought,"bottles")
return bottlesbought
You can give it a default value so you don't need to specify that it's equal to zero at the start (which it always is).
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
I am learning python and CS via the MIT OCW material. Doing this for fun btw because I think its interesting. I am trying to tackle a problem set where for a given credit card balance (ex. $1200) and interest rate (18%), what would minimum monthly payment need to be pay it off completely in 12 months or less. Start with $100 and if more or less is needed, change it increments of $10. In my code below, if the initial start of $100 doesnt work, i dont know how to increase it by 10 and THEN start iterating again. Im not even sure starting with a "While" is the best approach. Im sure the pros could code this up in like 2 lines but I would appreciate if anyone were to help, they do it the long way so a novice like myself could follow it.
balance = float(input("Enter the outstanding balance on your credit card:"))
annual_rate = float(input("Enter the annual credit card interest rate as a decimal:"))
monthly_interest_rate = annual_rate / 12.0
minimum_monthly_payment = 100
updated_balance_each_month = balance * (1 + monthly_interest_rate) - minimum_monthly_payment
month = 1
while month <= 12:
month += 1
updated_balance_each_month = updated_balance_each_month * (1 + monthly_interest_rate) - minimum_monthly_payment
if updated_balance_each_month <= 0:
print ("Monthly payment to pay off debt in 1 year:", minimum_monthly_payment)
print ("Number of months needed:",month)
print (round(updated_balance_each_month,2))
break
else:
minimum_monthly_payment += 10
So in programming you can create functions. These are blocks of code that you can call from elsewhere that will execute what you put in them. For python the syntax looks like...
def function_name(parameter1, parameter2, parameterN):
#function code here
#optional return statement
return parameter1 + parameter2
So what you could try is putting your while loop inside a function and if the while loop is successful, return true, and if it fails return false. Then in your main you can choose to redo the function if it returns false. So here is an example of how you could fix your problem.
def try_to_pay_off(payment, interest_rate, start_balance):
month = 0
updated_balance = start_balance
while month <= 12:
month += 1
updated_balance = updated_balance * (1 + interest_rate) - payment
if updated_balance <= 0:
return True
# will return false if it goes through 12 months and debt not payed off
return False
def Main():
balance = float(input("Enter the outstanding balance on your credit card:"))
annual_rate = float(input("Enter the annual credit card interest rate as a decimal:"))
done = False
monthly_payment = 100
while not done:
if try_to_pay_off(monthly_payment,annual_rate,balance):
done = True
else:
monthly_payment += 10
# after finding the monthly payment required
print ("Monthly payment to pay off debt in 1 year:", monthly_payment)
This way you keep running your function with new values until it finds a monthly payment that can pay off your balance with interest rate in one year.
First off, welcome to StackOverflow, and I hope you enjoy the world of programming. I have heard MIT OCW is a great resource, so best of luck to you and whatever you're going to do.
If I understand the question correctly, you must find the smallest minimum payment (which is the same across all twelve months) that will pay off the debt. (I currently don't have commenting privileges, so if I misunderstand the question, I'd appreciate it if you clarified.)
To answer your question in the title, to "re-initiate iteration," you would create a second loop outside the first. Here's some example code.
# given balance and annual_rate
monthly_interest_rate = annual_rate / 12.0
minimum_monthly_payment = 100
# debt_is_paid_off is a use for a variable called a one-way flag
debt_is_paid_off = False
while not debt_is_paid_off:
updated_balance_each_month = balance
# range is a neat little python trick to go from 1 to 12 easily
for month in range(1, 13):
# update the balance
updated_balance_each_month *= (1 + monthly_interest_rate)
updated_balance_each_month -= minimum_monthly_payment
# check if it's paid off
if updated_balance_each_month <= 0:
debt_is_paid_off = True
print ("Monthly payment to pay off debt in 1 year:",
minimum_monthly_payment)
print ("Number of months needed:",month)
print (round(updated_balance_each_month,2))
# note that this only breaks out of the for-loop.
# so we need debt_is_paid_off to exit out.
break
minimum_monthly_payment += 10
Note how there are two loops in the code. The outer loop keeps increasing which minimum payment to try until the debt is paid off, and the inner loop simulates paying off the debt by repeating twelve times.
However, the standard approach - just using the "break" keyword, as you did - doesn't work in Python if there are two loops. It only breaks out of the first. So we use this new variable, debt_is_paid_off, to get us out of that second loop.
ok thanks guys for the help but I ended up coming up with a solution myself (!!!). I figured out that in the code I originally posted, it would do the calculation for month 1 then check to see if updated_balance_each_month was less than 0 and if not increase monthly minimum by 10 for each month after that until balance was equal to or below 0 instead of running through all 12 months and then increasing monthly minimum by 10. so you can see that I added another IF statement so that monthly minimum only increased if month == 12 and balance was above 0 and it worked! Now, can anyone tell me how I can add code here so that it shows up properly? I click on the {} and then paste my code where it says so but it always comes up jumbled...
balance = float(input("Enter the outstanding balance on your credit card:"))
annual_rate = float(input("Enter the annual credit card interest rate as a decimal:"))
monthly_interest_rate = annual_rate / 12.0
minimum_monthly_payment = 100
updated_balance_each_month = balance * (1 + monthly_interest_rate) - minimum_monthly_payment
month = 1
while month <= 12:
month += 1
updated_balance_each_month = updated_balance_each_month * (1 + monthly_interest_rate) - minimum_monthly_payment
if updated_balance_each_month <= 0:
print ("Monthly payment to pay off debt in 1 year:", minimum_monthly_payment)
print ("Number of months needed:",month)
print (round(updated_balance_each_month,2))
break
if month == 12 and updated_balance_each_month > 0:
minimum_monthly_payment += 10
month = 0
updated_balance_each_month = balance
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.