Apologies, at times i struggle with basics of python. The below code is not working.
def cost(c,r,t)
total cost = c*(1+r)*(1+t)
print total cost
cost(44.5, 6.75%, 15%)
I'm trying to find the computed total cost of meal based on the following:
Cost of meal: $44.50
Restaurant tax: 6.75%
Tip: 15%
Your function can just return the cost, rather than print it out within itself.
def cost(cost, rate, tip):
return cost*(1+rate)*(1+tip)
print cost(44.5, 0.0675, 0.015)
def cost(c,r,t):
total_cost = c*(1+r)*(1+t)
print total_cost
cost(44.5, 6.75/100, 15/100)
The percentage sign is a special character in Python. Replacing % sign solves the syntax error.
Related
it asks for sales tax, but then prints a long number for total tax
#This program will ask user for sales and calcutate state, county, and total sales tax.
#This module calculates the county tax
def askTotalSales():
totalSales=float(input("Enter sales for the month: "))
print()
return totalSales
def countyTax(totalSales):
countyTax= .02
return totalSales*countyTax
def stateTax(totalSales):
stateTax= .04
return totalSales *stateTax
#This module calculates the state tax
#this module will calculate total sales tax
def calcTotalTax(stateTax, countyTax):
totalTax=stateTax+countyTax
print()
return totalTax
#printData
def printTotalTax (countyTax, stateTax, totalTax):
print ('County sales tax is'+countyTax)
print('State sales tax is' +stateTax)
print('Total sales tax is' +totalTax)
def main():
totalSales=askTotalSales()
countySales=countyTax(totalSales)
stateSales=stateTax(totalSales)
totalTax=float(input(calcTotalTax))
main()
an online class with zero instruction is not ideal, i've pored throjugh these pages and some youtube videos to come up with this
i understand the issue may be with my Cacltotal tax function- i'm unsure of how to call it
The problem is with this line:
totalTax = float(input(calcTotalTax))
calcTotalTax is a function, not a number. The program will print the function address (which should seem like a random large number) rather than an output. This should be,
totalTax = float(calcTotalTax(stateSales, countrySales))
Pay careful attention to which arguments each function takes (it's specified when you def the function), and make sure you're passing those arguments when you call the function. Also, be careful not to give variables the same names as your functions; each name can only refer to one thing at a time.
In real life you usually don't want print calls in all of your functions, but since you had them in your original code I added strings to them that let you see which function is being called when:
def ask_total_sales():
return float(input("Enter sales for the month: "))
def calc_county_tax(total_sales):
print("Calculating county tax...")
return total_sales * 0.02
def calc_state_tax(total_sales):
print("Calculating state tax...")
return total_sales * 0.04
def calc_total_tax(county_tax, state_tax):
print("Calculating total tax...")
return county_tax + state_tax
def print_total_tax(county_tax, state_tax, total_tax):
print ('County sales tax is', county_tax)
print('State sales tax is', state_tax)
print('Total sales tax is', total_tax)
def main():
total_sales = ask_total_sales()
county_tax = calc_county_tax(total_sales)
state_tax = calc_state_tax(total_sales)
total_tax = calc_total_tax(county_tax, state_tax)
print_total_tax(county_tax, state_tax, total_tax)
if __name__ == '__main__':
main()
Note that (for example) in the main function above, we call the function calc_total_tax with the arguments county_tax and state_tax, and what it returns gets assigned to the value total_tax, which we then pass to print_total_tax along with county_tax and state_tax (which we got by calling calc_county_tax and calc_state_tax).
Enter sales for the month: 500
Calculating county tax...
Calculating state tax...
Calculating total tax...
County sales tax is 10.0
State sales tax is 20.0
Total sales tax is 30.0
I'm creating a program that calculates the total cost of a meal by taking the following inputs:
meal_cost,tax_rate,tip_rate,number_eating
and printing them inside a string with a function call. I looked up on StackOverflow, but could not find a question that suited my situation (printing a dictionary returned from a function in a string)
I have a single function that takes all the inputs and returns a dictionary output. I want to print those returned values in a string with a function call, all in the same line. This is what I tried:
def calculatedCost(meal_cost,tax_rate,tip_rate,number_eating):
tax = round(float(meal_cost * tax_rate) / 100,2)
tip = round(float(meal_cost * tip_rate) / 100,2)
total_cost = round(meal_cost + tax + tip,2)
division = round(total_cost / number_eating,2)
return {'tax': tax, 'tip': tip, 'total_cost':total_cost, 'division':division}
print("The cost of your meal is: {total_cost}, the tax on your meal is: {tax}, the tip is equal to: {tip}, and the split total is: {division}".format(calculatedCost(62.75,5,20,2)))
and I get this error: (I'm using Processing)
KeyError: total_cost
processing.app.SketchException: KeyError: total_cost
at jycessing.mode.run.SketchRunner.convertPythonSketchError(SketchRunner.java:240)
at jycessing.mode.run.SketchRunner.lambda$2(SketchRunner.java:119)
at java.lang.Thread.run(Thread.java:748)
you need to unpack the dict (note the double asterisk):
print("The cost of your meal is: {total_cost}, the tax on your meal is: {tax}, the tip is equal to: {tip}, and the split total is: {division}".format(**calculatedCost(62.75,5,20,2)))
Hello I'm a college student whose just begun to take a computer programming class and have hit a bit of a snag I'm struggling to figure out. The program I'm supposed to create using python is a car sales program that calculates the weekly gross pay that is the total of made from the cars sold in the week. I have to input the number of cars sold and the value given back should be how much was made that week, this is the code I have written :
def main():
car_number = float(input('enter number cars sold'))
def calculate_total('car_number,price,commission'):
price = 32,500.00
commission = .025
total = car_number * price * commission
return total
main()
on the line 'def calculate_total('car_number, price, commission'): I am receiving a syntax error declaring 'formal parameter expected' How do I fix this issue?
That line should be
def calculate_total(car_number,price,commission):
You are instead writing a string there.
Also, as you are changing the values of price and commission it is better defined as
def calculate_total(car_number):
You have forgotten to call the function at the end
return calculate_total(car_number)
def calculate_total('car_number,price,commission'): this line should be
def calculate_total(car_number):
Ok so, I have an assignment to make a carsales program which is suppose to calculate how much the salesperson will make in a week. I already know how much all the cars sell for and how much commission he makes. Here is my code:
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
def calculate_total(car_number,price,commission_rate):
price = 32,500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
return calculate_total(car_number)
print('The weekly gross pay is $',calculate_total)
main()
The program isn't working for some reason but I decided to submit it to my professor anyway. He then replied by saying that I wasn't asked to create a new function and that I have to delete it and work just in main. Can someone please tell me what this means?
Two things:
'Working in main' as your professor said means that you don't define any functions. All your code just sits in the file, without any def ... statements. I know that's probably not clear. Here's an example:
import os
print "Your current working directory is:"
print os.getcwd()
This kind of programming has more the feel of a 'script' - you're not defining parts of the program that you're going to use more than once, and you're not taking the trouble to break down what the program does into single-purpose functions.
Second, you've entered price in such a way that Python thinks you're creating a tuple of numbers instead of a single value.
price = 32,500.00 is interpreted by Python as creating a tuple, with values 32 and 500.00 in it. What you actually want is: price = 32500.00.
I broke down and completed the process for you.
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
price = 32500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
print('The weekly gross pay is $',calculate_total)
Sorry i did not saw the complete question before but anyway this is the correct answer without a function
The keywords try and except are for error handling. If you give as input something invalid let's say a letter instead of number will throw a message
(Could not convert input data to a float.)
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
#before: car_number = float(raw_input('Enter number of cars sold :'))
car_number = float(input('Enter number of cars sold :'))
except ValueError:
#before: print 'Could not convert input data to a float.'
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))
main()
If you don't even want main() function here is the answer:
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
car_number = float(input('Enter number of cars sold :'))
except ValueError:
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))
UPDATED:
This Code Works:
# North Carolina Sales Tax Estimator
# Estimates the Amount of Tax You Should Pay in North Carolina
# Defines the Current 2012 Tax Rate
nctaxrate = 0.07
# Defines the tax variable by multipling subtotal by the current nc tax rate
# tax = subtotal * nctaxrate
# Defines the total variable by adding the tax variable to the subtotal variable
# total = subtotal + tax
# Defines the Subtotal from an Input of the User's Purchase Amount
def main():
print("\t\t\tThis is the NC Sales Tax Estimator")
print("\t\t Input Your Total Purchases Below\n")
while True:
subtotal = float(input("Enter the total price of your purchases:\t$").strip())
if subtotal == -1: break
tax = subtotal * nctaxrate
total = subtotal + tax
print("\tSUBTOTAL: $", subtotal)
print("\t TAX: $", tax)
print("\t TOTAL: $", total)
# if this script is called directly by Python, run the main() function
# (if it is loaded as a module by another Python script, don't)
if __name__=="__main__":
main()
Here is the Original Question:
So I am learning Python and asked a previous question yesterday and was supplied with an awesome set of code that I decided to modify to work with an NC Sales Tax Estimator Program I wanted to create.
The one thing is that I am getting a break out loop error that I don't quite understand. I've searched and tried to understand the meaning but I know the code worked before. Also the tax code program I created from scratch :) worked before trying to add the fancy ability to submit many inputs in a loop until the user wanted to 'exit'.
Here is the Code:
# North Carolina Sales Tax Estimator
# Estimates the Amount of Tax You Should Pay in North Carolina
# Defines the Current 2012 Tax Rate
nctaxrate = 0.07
# Defines the tax variable by multipling subtotal by the current nc tax rate
tax = subtotal * nctaxrate
# Defines the total variable by adding the tax variable to the subtotal variable
total = subtotal + tax
# Defines the Subtotal from an Input of the User's Purchase Amount
def main():
print("\t\t\tThis is the NC Sales Tax Estimator")
print("\t\t Input Your Total Purchases Below")
while True:
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
if subtotal.lower()=='exit':
break
try:
subtotal = int(subtotal)
except ValueError:
print("That wasn't a number!")
try:
print("\tSUBTOTAL: $", subtotal)
print("\t TAX: $", tax)
print("\t TOTAL: $", total)
except KeyError:
print("")
# if this script is called directly by Python, run the main() function
# (if it is loaded as a module by another Python script, don't)
if __name__=="__main__":
main()
P.S. I only added the KeyError because I researched that you must have an error statement after a try. I'm just a beginner so I'm attempting to create programs myself and reading "Python for the Absolute Beginner".
UPDATE:
I fixed the indentation but now I get the following traceback error:
Traceback (most recent call last):
File "C:/LearningPython/taxestimator.py", line 30, in <module>
tax = subtotal * nctaxrate
NameError: name 'subtotal' is not defined
I thought I defined it in the input ie.
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
Is it because the other defines (tax and total) that use the defined subtotal are defined before subtotal is defined? I tried moving them below the defined subtotal but it didn't work still.
Thanks for any Advice.
Best,
Steven
The main issue that you have is that Python requires whitespace to scope methods. Without that, then statements will run not as intended - for example:
while True:
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
if subtotal.lower()=='exit':
break
will not break out of the loop with valid input (it will if you put a string there, but that's another matter). Also, if everything is to be in the scope of main(), every statement requires one level of indentation (or four lines of whitespace, if you prefer). As it stands, your while won't run in the scope of main().
Also, you make reference to subtotal before you actually give it a value. Since subtotalwasn't properly initialized, you won't have a value to use for it.
You would want to rewrite your code such that tax and total are defined after you define subtotal.
while True:
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
if subtotal.lower()=='exit':
break
tax = subtotal * nctaxrate
total = subtotal + tax
Finally, if subtotal, total, and tax are properly defined (which, after the above, they will be), there will be no need for the superflous try...except statement when you wish to print the values out.
if subtotal.lower()=='exit':
break
needs to be indented probably ... unless that was just a typo when entering the question