calling calculating functions in Python - python

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

Related

Stadium Seats Python program need assistance to set amount with two decimal points

I have to correct this python program I am trying to set the dollar amounts to 2 decimal points. So far this is what i have done but still is not showing two decimal points!
Instructions are below:Python
"Write a program that asks how many tickets for each class of seats were sold, then displays the amount of income generated from ticket sales. There are three seating categories at the stadium. Class A seats costs $20, Class B seats cost $15, and Class C seats cost $10."
Assume the user will enter valid data (Integer/Float).
Declare Global variables, Local variables and Global constants as needed in the program
Write and call function ShowIncome to calculate and display total income generated from ticket sales for all three Class seating categories.
The program should round the amount of income generated from ticket sales to a maximum of two decimal places.
def calcIncome(n,c):
if c=="A":
return n * 20
if c=="B":
return n * 15
if c=="C":
return n * 10
def showIncome(a,b,c):
total=a+b+c
print("Income from class A seats:$",a)
print("Income from class B seats:$",b)
print("Income from class C seats:$",c)
print("Total income:$",total)
def main():
a=int(input("Enter count of A seats: "))
b=int(input("Enter count of B seats: "))
c=int(input("Enter count of C seats: "))
aIncome=calcIncome(a,"A")
bIncome=calcIncome(b,"B")
cIncome=calcIncome(c,"C")
showIncome(aIncome,bIncome,cIncome)
main()
Try changing your 'showIncome' function:
def showIncome(a,b,c):
total=a+b+c
print("Income from class A seats:$",a)
print("Income from class B seats:$",b)
print("Income from class C seats:$",c)
total = (round(float(total), 2))
print("Total income:$","{:0,.2f}".format(total))
(round(float(total), 2))) -
This will round your total income into two decimal places after converting the value to 'float'.

Calling a function that's inside another function from a function

To be more specific, I want to call the function get_hours_worked from inside
calc_gross_pay. I realize that another way to do this is to just pass arguments into calc_gross_pay, but I was wondering if what I was trying to do is possible. I have a feeling it's not. Thanks for any help.
def main():
#
print("This employee's gross pay for two weeks is:",calc_gross_pay())
def get_input():
def get_hours_worked():
#get_hours_worked
x = float(input("How many hours worked in this two week period? "))
return x
def get_hourly_rate():
#get_hourly_rate()
y = float(input("What is the hourly pay rate for this employee? "))
return y
def calc_gross_pay():
#
gross = get_input(get_hours_worked) * get_input(get_hourly_rate)
return gross
main()
Here's a reorganized version of your code. Rather than defining get_hours_worked and get_hourly_rate inside get_input we define them as separate functions that call get_input.
def get_input(prompt):
return float(input(prompt))
def get_hours_worked():
return get_input("How many hours worked in this two week period? ")
def get_hourly_rate():
return get_input("What is the hourly pay rate for this employee? ")
def calc_gross_pay():
return get_hours_worked() * get_hourly_rate()
def main():
print("This employee's gross pay for two weeks is:", calc_gross_pay())
main()
demo
How many hours worked in this two week period? 50
What is the hourly pay rate for this employee? 20.00
This employee's gross pay for two weeks is: 1000.0
As PM 2Ring pointed out, its better to change the hierarchy itself. But in case you want the same still, proceed as follows :
def get_input():
def get_hours_worked():
x = float(input("How many hours worked in this two week period? "))
return x
def get_hourly_rate():
y = float(input("What is the hourly pay rate for this employee? "))
return y
return get_hours_worked, get_hourly_rate # IMP
def calc_gross_pay():
call_worked, call_rate = get_input() # get the functions
gross = call_worked() * call_rate() # call them
return gross
def main():
print("This employee's gross pay for two weeks is:",calc_gross_pay())
#How many hours worked in this two week period? 3
#What is the hourly pay rate for this employee? 4
#This employee's gross pay for two weeks is: 12.0
main()

Calculating cost of meal with taxes

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.

Python car sales code issue

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

Break Outside Loop with Previous Example

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

Categories