python challenge help solving it - python

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

Related

Coffee Machine - invalid syntax and End of Statement expected in new function

So I'm trying to create a coffee machine program (you choose a drink, the machine checks the ingredients, the resources and the money you insert, then it dispenses the drink.) and it went okay until I got to the part where the program processes the coins and, if sufficient, adds them to the amount of money in the machine.
I'm not really good with return statements and global vs local scopes, so I assume they are the issue. I tried googling, but nothing came up that actually solves the specific problem I have.
This is the code for the function in question:
def process_coins(order, money):
print("Please insert coins.")
quarters = float(input("Quarters: ")) * quarters_value
dimes = float(input("Dimes: ")) * dimes_value
nickles = float(input("Nickles: ")) * nickles_value
pennies = float(input("Pennies: ")) * pennies_value
total = quarters + dimes + nickles + pennies
if total < MENU[order]["cost"]:
total = 0
return print("Sorry, that's not enough money. Money refunded.")
else:
return money += total
PyCharm tells me "End of Statement expected" and "invalid Syntax" for the last line.
When I remove "return" it runs but doesn't actually add the total to the money in the machine. I also tried putting brackets around money += total, which turns both problems into "unexpected expression syntax".
I honestly don't understand why this doesn't work. I just want pycharm to add "total" (local scope) to "money"(global scope) and to return it so I can use it in the rest of the code.
I also don't understand why this function wasn't able to work with the variable "money" before I added it as an argument in the brackets, but it was able to work with the variables "dimes_value" etc. just fine, even though those are mentioned just one line before "money" at the start of the code and aren't part of the arguments in the bracket of the function.
What am I missing?
The problem is that return can only return expressions, but an augmented assignment is a statement. This is why you get a syntax error.
For Python >= 3.8, you can use an assignment expression to overcome this:
return (money := money + total)
* Note the necessary parenthesis.
This will both assign to money and return the value assigned to it.
But this will create a new problem: money will now be considered a local variable (because you assign to it inside the function) and you'll get a different error.
To overcome this, you will need to declare
global money
At the start of the function.
But really the best solution here is not to use global variables at all, simply return money + total, and assign the returned value in the global scope, where you call the function.
if total < MENU[order]["cost"]:
total = 0
return print("Sorry, that's not enough money. Money refunded.")
else:
money += total
return money

How was this percentage increase applied?

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.

How do I create a financial program where I can continuously input amount and show remaining amount in dollars

Trying to create a financial calculation program. I know I have to use loop but how do I loop continuously when the user input float value? I believe I'm wayyyyy off but I am quiet curious how this program can be written for myself so I can utilize this.
I would like something like if I input 10000 then ask for another input for expense... This would give me remaining till I stop input. So it would look something like this
10000 #income
3400 # expense
6600 # remaining
600 #transportation
6000 #remaining
100 #utility expense
5900 #remaining
Do I have the concept right?
def financial_plan ():
c = input ("How much income do you have? ")
income = ()
y = input ("expense?")
expense = ()
z = (income - expense)
for income1 in z:
income1 -= y
print(income1)
This seems like a homework, but still you are a bit on right track so I am answering it for you. Note that you need to convert the input to float, other way around doesn't works.
Few points to clarify your doubts:
If you don't know how many times the loop will run, use while loop.
Use the input function to take input, and apply the float on it to get float value of it.
Put the code inside the function it is supposed to be in if you want it work.
Call the function at the end of the program cause Python is not like C like languages with main function which is called by default.
It is a python code.
def financial_plan ():
income = float(input("How much income do you have? "))
while True:
expense = float(input("Expense: "))
if (income >= expense):
income = income - expense
print("You have remainder balance: " + str(income))
else:
print("Insufficient account balance!!")
continue
if (income == 0):
print("Balance Nil!")
print("Program Ended!")
financial_plan()

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

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.

Categories

Resources