Break Outside Loop with Previous Example - python

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

Related

calling calculating functions in 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

Tax discount for item calculator

How do i make a code where user input if rhe item they want has tax and then discount and then they input the percent of discount and all these price are added to the total cost
it is an easy concept , it will be something like this:
earnings = int(input("Insert your earnings : "))
taxes = 0.20
if earnings < 10000:
totTaxes = int(earnings * 0.20)
salary = earnings - totTaxes
print("Your Salary is ", salary)
print("The taxes amount are : ", totTaxes)
i think you are new in python, u can copy and run this script on python idle , its a simple python scrpts IDE that executes the scripts
this is the link to download it for windows LINK.
Good luck!

How do I implement a finance function into this program?

I'm having trouble implementing a function into this program. The program I have currently works fine on its own without the function but I still need to find a way to put def finance(income, salesPrice): into it. I also need to invoke the function with this: print(finance(income, salesPrice)). I tried different ways but whenever I try to invoke the function, it says that income is not defined.
This is what I have to make:
The function will test whether a person is qualified to finance an expensive car. They are qualified if their annual income is greater than $100,000 and the sales price is less than $1,000,000. The function returns a message to the program stating whether the person is qualified or not. The program invokes the finance() function with this print statement: print (finance (income, salesPrice)) and the user input the income and sales price.
def finance(income,salesPrice):
income = float(input("Please enter annual income: "))
while (income <= 0):
income = float(input("Invalid input! Please enter positive value: "))
income += 1
salesPrice = float(input("Please enter sales price of car: "))
if (income>100000 and salesPrice<1000000):
print("You are qualified to purchase this car.")
else:
print("You are not qualified to purchase this car.")
result = print(finance(income,salesPrice))
The problem is indentation + You need to return a variable. EDIT: I edited the code based on your problem
def finance(income, sales_price):
if income > 100000 and sales_price < 1000000:
return "You are qualified to purchase this car."
else:
return "You are not qualified to purchase this car."
salesPrice = float(input("Please enter sales price of car: "))
income = float(input("Please enter annual income: "))
while income <= 0:
income = float(input("Invalid input! Please enter positive value: "))
income += 1
print (finance (income, salesPrice))
You make an indentation error, your line while (income <= 0) is outside of your function, you have to indent it.
More informations about indentation in python here.

How do you use a loop for a function?

I have written most of the codes already, but I am still having a hard time figuring out the code to loop the program (for a function) as many times the user desires until the user is done. Also, I am unable to use a For loop.
def load():
a=input("Name of the stock: ")
b=int(input("Number of shares Joe bought: "))
c=float(input("Stock purchase price: $"))
d=float(input("Stock selling price: $"))
e=float(input("Broker commission: "))
return a,b,c,d,e
def calc(b,c,d,e):
w=b*c
x=c*(e/100)
y=b*d
z=d*(e/100)
pl=(x+z)-(y-z)
return w,x,y,z,pl
def output(a,w,x,y,z,pl):
print("The Name of the Stock: ",a)
print("The amount of money Joe paid for the stock: $",format(w,'.2f'))
print("The amount of commission Joe paid his broker when he bought the stock: $",format(x,'.2f'))
print("The amount that Jim sold the stock for: $",format(y,'.2f'))
print("The amount of commission Joe paid his broker when he sold the stock: $",format(z,'.2f'))
print("The amount of money made or lost: $",format(pl,'.2f'))
def main():
a,b,c,d,e=load()
w,x,y,z,pl=calc(b,c,d,e)
output(a,w,x,y,z,pl)
main()
To let the user decide if they want to keep looping and not any fixed number of times, ask the user:
# in place of the call to main() above, put:
while input('Proceed? ') == 'y':
main()
So it keeps looping over main() as long as the user enters 'y'. You can change it to 'yes', 'Yes', etc. as needed.
Side note:
1. You should use more than 1 space for indent. Typically 4 spaces, or at least 2.
2. read up on if __name__ == "__main__".
Calling a function in a loop is fairly simple, you wrap in either in a while or a for loop and call it inside. The below code executes the brookerage function 10 times. I suppose you can use this as an example and customize the entire thing for your needs.
def brookerage():
a,b,c,d,e=load()
w,x,y,z,pl=calc(b,c,d,e)
output(a,w,x,y,z,pl)
def main():
for i in range(0,10):
brookerage()
main()

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

Categories