If statements and Variables - python

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

Related

Wriring a code in python for profitability

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

I'm doing python course on mooc.fi but im stuck on "Food expidenture"

# 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.

A Small Python 2.5.4 Program: Does This Code Do The Desired Job?

I'm learning the Python 2.5.4 programming language using the MIT OCW Scholar course 6.00.
I have written a program, but with the same input, my program's output differs from the output that the MIT people have shown the program to produce.
I wish to write a Python 2.5.4 program that will get current outstanding balance and annual interest rate as input from the user, and then uses the bisection search method to find the minimum fixed minimum monthly payment that would cause the balance to fall below zero within 12 months. Then the program displays the right monthly amount, the number of months needed to claer the outstanding amount, and the final balance.
Here's my code:
# Start of code
balance = float(raw_input('Enter the outstanding balance on your credit card: '))
interestRate = float(raw_input('Enter the annual credit card interest rate as a decimal: '))
lower = balance / 12.0
upper = ( balance * ( 1 + interestRate / 12.0 ) ** 12.0 ) / 12.0
payment = ( lower + upper ) / 2.0
currentBalance = balance
while currentBalance > 0:
for months in range(1, 13):
currentBalance = currentBalance * ( 1 + interestRate / 12.0 ) - payment
if currentBalance <= 0:
break
if currentBalance <= 0:
break
else:
lower = payment
payment = ( lower + upper ) / 2.0
currentBalance = balance
print 'RESULT'
print 'Monthly payment to pay off debt in 1 year:', '$' + str(round(payment, 2))
print 'Number of months needed:', months
print 'Balance:', '$' + str(round(currentBalance, 2))
#End of code
Does my code do the desired job? If not, where lies the problem? And, how to fix it? Even if the program is right, in what ways can it be improved?
Please do bear in mind that I'm a only a beginner.
Regards.
You have a couple of typos (which may have been introduced when copying into your posting):
you split balance on your credit / card: across a line-ending, which will give a SyntaxError
currentBalance = currentBalance * ( 1 + interestRate / 12.0 ) payment is missing a - operator before payment
The first logical error is
if currentBalance <= 0:
break
... you stop as soon as you find a higher than needed payment; you only ever increase possible payment values (lower = payment), never decrease it (you should have a clause leading to upper = payment, otherwise your bisection search will be lopsided).
Once you do that, you will have to add a new test to know when to stop looping. What is your target accuracy - payment to the nearest cent? How will you know when you have found it?
My only other suggestion would be to improve your code organization by defining some operations as functions - get_float(prompt) and final_balance(current_balance, interest_rate, num_payments) are obvious candidates.

Python Sales Tax Program with 2 Decimal Places, Money

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.

python challenge help solving it

the reason i have signed up here today is to ask for a hint to where i'm going wrong in this argument. i am very new to coding and was hoping i might be able to get some help. i feel i'm slightly cheating myself by asking for help so early, so if someone can explain where I've made mistakes i would like to try and figure out how to correct them, clues and hints would be appreciated but i would really like to understand where the errors are what to do to correct them and why, so please don't just paste the answer. thanks
ok here is my attempt at Writing a Car salesman program where the user enters the base price of a car. The program should add a bunch of extra fees such as tax, license, dealer prep, and destination charge. Make tax and license a percent of the base price. The other fees should be set values. Display the actual price of the car once all the extras are applied.
base_price = float(input("please enter base price of car",))
taxes *=0.06
float(input(taxes))
licence *= 0.01
float(input(licence))
premium_pack += 1250
print("premium pack + 1250")
total_price = base_price + premium_pack + taxes + licence
print("\n\total price:", total_price))
input("\n\npress enter key to exit")
the last time i ran the program i had a name error
taxes *= 0.06
NamError: name 'taxes' is not defined
o.k. i hope this information helps and thank you for your time in advance
alex
taxes*=0.06 is shorthand for taxes = taxes * 0.06. Which you have not yet defined. I think what you actually meant to write was
taxes = base_price * 0.06
You'll still have other issues with this program, though.
taxes *= 0.06 is shorthand for taxes = taxes * 0.06, , i.e., the new value of taxes is 0.06 times the old value of taxes. Thus the interpreter is complaining that you haven't defined taxes before using it on the right hand side.
Presumably what you want is:
taxes = 0.06 * base
or
taxes = 0.06 * float(raw_input('Enter amount to be taxed'))
You seem to be unclear on what the *= and += operators do. What you want is to assign taxes (and the other variables) some values equal to base_price * 0.06 and so on. Use the = operator to assign values to a variable (like you did in the first line), and the * operator to multiply two values together (e.g. base_price * 0.06).
You've got this problem in several places, as well as an issue where I think you don't know what the input function does: if you just want to display a value, you should use the print function.
I highly recommend going through the tutorials. They do a good job covering this sort of stuff.
The line taxes *= 0.06 means, taxes = taxes * 0.06. Python is telling you that it doesn't know what the value of taxes is (because you haven't assigned it a value).
licence and premium_pack have the same issue.
You are incorrectly using the *= and += statements.
You can't use the taxes *=0.06 statement unless you have defined taxes previously. Same is the case with licence and premium_pack.
Also, the statement float(input(taxes)) is wrong, you need to pass a string as an argument to it. (http://docs.python.org/3/library/functions.html#input)
Next, if you are using python 2.7, the usage of the input statement is incorrect - you should use raw_input instead. (https://stackoverflow.com/a/3800862/1860929)
There is an extra closing bracket in print("\n\total price:", total_price)) statement
You are using an extra \ after \n due to which, the t of total will get escaped.
Finally, you need to check the logic itself. As #Wayne has pointed in his answer, you probably want to do taxes = base_price * 0.06 and not taxes = taxes * 0.06
Check the following code, I think you are looking for something similar
base_price = float(raw_input("Please enter base price of car",))
taxes = 0.06 * base_price
print("Taxes: %s" %taxes)
licence = 0.01 * base_price
print("Licence: %s" %licence)
premium_pack = 1250
print("premium pack: 1250")
total_price = base_price + premium_pack + taxes + licence
print("\ntotal price: %s" %total_price)
raw_input("\n\npress enter key to exit")

Categories

Resources