How was this percentage increase applied? - python

I wrote a conditional statement in Python which increases a price depending on the corresponding state's tax rate at the time.
In the example below, I set the purchase_amount to $17 and the state to CA. The tax rate is 7.5%. Here's is how I formulated it to get the correct answer of $18.275.
state = "CA"
purchase_amount = 17
if state == "CA":
tax_amount = .075
elif state == "MN":
tax_amount = .095
elif state == "NY":
tax_amount = .085
total_cost = tax_amount * purchase_amount + purchase_amount
However, I saw someone use a different formulation, as seen below, to get the same exact answer.
if state == "CA":
tax_amount = .075
total_cost = purchase_amount*(1+tax_amount)
I have never seen a percentage applied this way before.
My MAIN QUESTION is...Where did the integer 1 even come from??
My second question is... Why was it added to the tax_amount before multiplying it by the purchase_amount?
This was especially alarming because while it is nice to have concluded with the same correct answer regardless, I aspire to adequately read the coding styles of others.
Thank you so much for your help!

Are you asking how to factor, like algebra 2 factoring. This would be called the distribution rule, the following lines are the same, by factoring out the common factor.
tax_amount * purchase_amount + purchase_amount
purchase_amount * ( tax_amount + 1 )

This is a math thing, if you want to add some % of the number to that number, you can do it two ways, your way:
(17 * .075) + 17 = 18.275
or their way:
17 * 1.075 = 18.275
these are both functionally the same calculation, just a different way of expressing it.

Related

If statements and Variables

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

Fairly New to Python - Global Varibable Issue

was wondering if I someone could lend a hand with the issue I am having with my python 3.4 code. I have found it hard to word my problem and searching the web for an answer has been difficult, so I thought it would be easier if I were to show the code and the issue to be resolved.
cola_cost = 2
surcharge = 0
def calc_takeaway(cost):
global surcharge
cost = cost * 1.05
surcharge = surcharge + (cost * 0.05)
cola_place = input("Do you want your cola to go? ")
if cola_place == "yes":
calc_takeaway(cola_cost)
print("$"cola_cost) ## cola cost should be $2.10 but instead prints out $2
print("$"surcharge)
Basically, my cola_cost will not change its global value after being passed into the calc_takeaway function. Sorry if this is too basic I would kist like to get this issue solved. Thank you.
EDIT: I'd also like to mention that I would like to use the function on different cost variables (i.e fanta_cost, water_cost...) as well.
Consider avoiding global in the first place if possible atleast when alternate methods are possible, because they are a bad usage. Instead of global, use simple parameter passing and function return concepts to handle the issue.
cola_cost = 2
surcharge = 0
def calc_takeaway(cost, surcharge):
cost = cost * 1.05
surcharge = surcharge + (cost * 0.05)
return cost, surcharge
cola_place = input("Do you want your cola to go? ")
if cola_place == "yes":
cola_cost, surcharge = calc_takeaway(cola_cost, surcharge)
print("$", cola_cost) # $ 2.10
print("$", surcharge)
Your global variable is sent by value, and so you're not really changing it,
but rather a copy of it. Here is a simpler example based on your code:
cola_cost = 2
def try_to_change_global_variable(cost):
cost = 174
try_to_change_global_variable(cola_cost)
print(cola_cost)
And when you run it you'll get:
$ python cola.py
2

Replacing Iteration with Recursion Python [duplicate]

This question already has answers here:
Is this function recursive even though it doesn't call itself?
(3 answers)
Closed 5 years ago.
I'm just starting to learn about recursion for an EdX course, and I've written an iterative function to calculate the remaining balance after paying the minimum required payment for 12 months.
I was able to easily do it with iteration, but I can't seem to wrap my head around the recursive way.
Please point me in the right direction.
Here is my iterative function
def remaining_balance_iter(balance,annualInterestRate, monthlyPaymentRate ):
'''
This code will take any balance and annual interest rate and calculate the
balance after one year of making the minimum payments
'''
month = 1
monthly_interest_rate = annualInterestRate/12.0
while month <= 12:
minimum_monthly_payment = monthlyPaymentRate * balance
monthly_unpaid_balance = balance - minimum_monthly_payment
balance = monthly_unpaid_balance + monthly_interest_rate*monthly_unpaid_balance
print( "Month {} Remaining balance: ".format(month) + str(round(balance,2)))
month += 1
print ("Remaining balance " + str(round(balance,2)))
I've made an attempt at a recursive function, but it needs work, and I need tutoring haha
def remaining_balance_recur(balance,annualInterestRate, monthlyPaymentRate, month ):
'''
This code will take any balance and annual interest rate and calculate the
balance after one year of making the minimum payments
'''
month = 1
monthly_interest_rate = annualInterestRate/12.0
while month <= 12:
minimum_monthly_payment = monthlyPaymentRate * balance
monthly_unpaid_balance = balance - minimum_monthly_payment
interest = monthly_interest_rate*monthly_unpaid_balance
balance = remaining_balance_recur(monthly_unpaid_balance, annualInterestRate, monthlyPaymentRate, month + 1) + interest
print ("Remaining balance " + str(round(balance,2)))
The best way I've found to deal with recursion is to start by specifying a base case. What is the condition that tells you when you've finished your method? In your code, it looks like you run your method until `month > 12', so your base case would be:
if month > 12:
return 1 # 1 for the purpose of explanation
Your return value for your base case is some base value of your function. What would your script return if your month was 12? That's the value you would return.
Next is the hard part. You have to figure out what variable is being modified by subsequent calls to your method. I'm not exactly sure what your code is intended to do, but it looks like you have a few calculations on some variables. When you use recursion, it's almost as if you're saving the state of the current method call you are executing while you go and retrieve the value you need for your statement. (e.g. a_num = 1 + recurse(n - 1) - you need the value of recurse(n - 1) before you can continue with this statement. This is only an example, though). Look for the variable that is affected by your previous iterations and try to make that recursive. In your situation, it looks like balance is that variable:
balance = balance + remaining_balance_recur(annualInterestRate, monthlyPaymentRate, month + 1)
return balance
When you write a recursive method, you always need to return some value at the end of the method, so the statement that called the method actually gets a value. Here's a short, useless example:
def recurse(n)
if n == 0 # BASE CASE
return 1
some_sum = 0
some_sum += recurse(n - 1) # I need the value from recurse(n - 1)
return some_sum # This method was called somewhere, so it needs to return
Try to figure out a recursive solution for your code from these hints. I'm sorry, recursion is very hard to explain especially over SO. Youtube vids and Google would also be a big help to understand recursion in general. Hope this gave you some ideas.
By putting "month = 1" before the while statement, you are resetting it so that while month <= 12 will run forever. This creates a "RecursionError: maximum recursion depth exceeded in comparison."
The output of your function is currently "NoneType" because its output is a print statement rather than returning an int or a float. This produces a "TypeError" because you have tried to add a float (the interest rate) to a NoneType (the printed statement) in your recursion.

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