Why can't my tax_a,b,c be found? - python

The purpose is to get the income from the user and apply a set of taxes based on the amount of money the user earns.
income = float(input('Enter your income: $ '))
if income < 35000:
tax_a = float((income * 0.15))
if (income - 35000) < 100000:
tax_b = float((income * 0.25))
if (income - 100000) > 100000:
tax_c = float((income * 0.35))
if income > 50000:
tax_s = (income * 0.05)
fed_tax = float((tax_a + tax_b + tax_c))
total_tax = (fed_tax + tax_s)
print('Your total tax liability is: ${:.2f}'.format(total_tax))
print('[details Federal tax: {:.2f}, State tax: {:.2f}'.format(fed_tax, tax_s))

You are only defining tax_a, tax_b, tax_c and tax_s if some condition is true. If the condition is not true, you leave the variable undefined.
I'm not a tax lawyer, but I assume the tax in a given category is 0 if the condition does not apply:
if income < 35000:
tax_a = float((income * 0.15))
else:
tax_a = 0.0
...and so on.

Need to initialize your variables and learn about "variable scope".
tax_a = tax_b = tax_c = tax_s = 0
income = float(input('Enter your income: $ '))
# ...

$ python incometax.py
Enter your income: $ 100000
Traceback (most recent call last):
File "incometax.py", line 15, in <module>
fed_tax = float((tax_a + tax_b + tax_c))
NameError: name 'tax_a' is not defined
The problem is that tax_a is only defined when a certain condition occurs. Since you always need these variables in the final calculation, you should define them at the beginning of your program:
tax_a = 0.0
p.s. Note that all of the float() calls are unnecessary if you initialize variables with floats to begin with and use floating point constants.

Related

Solving a purchasing algorithm program

So, I'm stuck at the moment.
I'm creating a program to calculate the complete sale if multiple, or singular, items are purchased. The program is also supposed to calculate a discount threshold and a state-sale's tax with the purchase. I can get the program to function, however, my end result is 0.0 dollars despite entries made. At this point, I can identify it is multiplying SOMETHING by 0, which I assume is the tax input, but I am at a total loss on how to correct this issue. Below is the code used.
#declarations
A_STATE_TAX = float(.056)
C_STATE_TAX = float(.029)
N_STATE_TAX = float(.05125)
U_STATE_TAX = float(.047)
state = ''
tax = float()
completeSale = ()
sockPrice = int(5)
sandalPrice = int(10)
shoePrice = int(20)
bootPrice = int(30)
quantityShoes = int()
quantitySocks = int()
quantityBoots = int()
quantitySandals = int()
quantityTotal = int()
quantityTotal = int(quantityTotal)
basePriceSocks = (quantitySocks * sockPrice)
basePriceShoes = (quantityShoes * shoePrice)
basePriceBoots = (quantityBoots * bootPrice)
basePriceSandals = (quantitySandals * sandalPrice)
baseTotal = int(basePriceSocks + basePriceShoes + basePriceBoots +basePriceSandals)
discount = float()
discountAnswer = (baseTotal * discount)
purchaseWithoutTax = baseTotal - (baseTotal * discount)
taxAnswer = purchaseWithoutTax * tax
#mainbody
print("This algorithm will calculate your purchase.")
#housekeeping()
print("How many shoes do you wish to purchase?")
input(quantityShoes)
print("How many socks?")
input(quantitySocks)
print("Boots?")
input(quantityBoots)
print("And sandals?")
input(quantitySandals)
#purchaseinfo()
quantityTotal = (quantityShoes + quantityShoes + quantityBoots + quantitySandals)
if quantityTotal < 6:
discount = 0
elif quantityTotal > 6 and quanityTotal < 10:
discount = .10
else:
discount = .20
purchaseWithoutTax = baseTotal - (baseTotal * discount)
#stateTax()
print("Please choose the following state: Arizona, New Mexico, Colorado or Utah.")
input(str(state))
if state == "arizona":
tax = A_STATE_TAX
elif state == "new mexico":
tax = N_STATE_TAX
elif state == "colorado":
tax = C_STATE_TAX
else:
tax = U_STATE_TAX
completeSale = (purchaseWithoutTax * tax) - taxAnswer
#endOfJob()
print(format(completeSale, '.2f'))
print("Your total is ", format(completeSale, '.2f'), " dollars.")
print("Thank you for your patronage.")
The main issue is that your baseTotal = 0 initially. And baseTotal = 0 because your quantities (e.g., quantityShoes) are initially 0. You shouldn't initialize values with int(), you should use 0 instead because it is more explicit. You multiply values with baseTotal so in the end you will get 0.
And as another answer mentions, you are using input incorrectly. For numeric quantities, you should convert the result of input to float or int, because input returns strings. You should also save the output to a variable name.
quantityShoes = int(input("How many shoes?"))
You can clean up your code by using dictionaries. That might help with debugging. Instead of having multiple quantity___ variables, you can use a dictionary that stores quantities (and prices, taxes, etc.).
state_taxes = {
"arizona": 0.056,
"colorado": 0.029,
"new mexico": 0.05125,
"utah": 0.047,
}
prices = {
"sock": 5,
"sandal": 10,
"shoe": 20,
"boot": 30,
}
input() doesn't work the way you used it. The argument that goes in input()
is printed before the user gives input. You did the equivalent of:
quantityShoes = int()
print("How many shoes do you wish to purchase?")
input(quantityShoes)
The first line sets quantityShoes equal to the default integer, which is 0. The second line prints that text. The third line line prints that number and waits for user input. You want to do something like:
quantityShoes = int(input("How many shoes do you wish to purchase?"))

name is not defined i have already defined the name

PFB the below code I am trying to calculate tax. why do I get the NameError: name 'tax' is not defined.
I have defined tax below still it throws the error tax not defined.
hw = float(input("Please enter total hours worked"))
hp = float(input("Please enter the hourly rate"))
# Pay and OT Calculations
rp = hp * hw
if hw == 40 or hw <40 :
ot = 0
tp = rp + ot
elif hw > 40 and hw <50 :
ot = (hw-40)*(hp*1.5)
tp = rp + ot
elif hw > 50 and hw < 60 :
ot = (hw-40)*(hp*2)
tp = rp + ot
elif hw > 60 or hw == 60 :
ot = (hw-40)*(hp*2.5)
tp = rp + ot
else :
print ("Thanks")
# tax Calculations
if tp == 200 :
tax = float((tp/100)*15)
elif tp > 200 and tp < 300 :
tax = ((tp-200)/100*20) + ((200/100)*15)
elif tp >300 and tp < 400 :
tax = ((tp-300)/100*25) + (((tp-200)-(tp-300))/100*20) + ((200/100)*15)
elif tp >400 and tp == 400 :
tax = ((tp-400)/100*30) + (((tp-200)-(tp-300)-(tp-400))/100*25) + (((tp-200)-(tp-300)/100)*20) + ((200/100)*15)
else :
print ("Thanks")
# Printing Results
print ("Your Salary has been credited")
print ("Regular Pay = ", rp)
print ("Overtime =", ot)
print ("Gross Salary before tax deductions = ", tp)
print ("Income Tax applicable =", tax)
you are using your variables across the entire function but are only defining them in the if/else cases. This adds a lot of room for error of missing a definition somewhere within a case as in
...
if tp == 200 :
tax = float((tp/100)*15)
elif tp > 200 and tp < 300 :
tax = ((tp-200)/100*20) + ((200/100)*15)
elif tp >300 and tp < 400 :
tax = ((tp-300)/100*25) + (((tp-200)-(tp-300))/100*20) + ((200/100)*15)
elif tp >400 and tp == 400 :
tax = ((tp-400)/100*30) + (((tp-200)-(tp-300)-(tp-400))/100*25) + (((tp-200)-(tp-300)/100)*20) + ((200/100)*15)
else :
# NO tax defined here
print ("Thanks")
...
You should define the function-scope variables on the top of your function as:
hw = float(input("Please enter total hours worked"))
hp = float(input("Please enter the hourly rate"))
rp = 0
ot = 0
tp = 0
tax = 0
# Pay and OT Calculations
...
# Printing Results
print ("Your Salary has been credited")
print ("Regular Pay = ", rp)
print ("Overtime =", ot)
print ("Gross Salary before tax deductions = ", tp)
print ("Income Tax applicable =", tax)
By setting these default values you are sure to never miss the variable initialization in your code and you will not need to add extra logic to handle the tax variable in the edge cases where it should not be changed (the else case in your question.

Variable is not defined in function

I'm currently working on the last function here, timeToRun.
I cannot figure out why I am receiving
NameError: name 'caloriesBurned' is not defined
I'm attempting to calculate the number of minutes it would take someone of a certain weight to burn off a number of calories while running.
weight = (int(input("Enter your weight in pounds ")))
while weight <= 40:
weight = int(input("Please reenter, weight must be higher than 40. "))
height = (int(input("Enter your height in inches ")))
while height <= 30:
height = int(input("Please reenter, height must be higher than 30. "))
age = (int(input("Enter your age in years ")))
while age <= 1:
age = int(input("Please reenter, age must be higher than 1. "))
def CalorieBurn(user_weight, user_height, user_age):
calories = 655 + (4.3 * user_weight) + (4.7 * user_height) - (4.7 * user_age)
print(calories)
def burnedRuns(user_weight):
caloriesBurned = user_weight * .095
print(caloriesBurned)
def burnedJogs(user_weight):
caloriesBurned = user_weight * .0775
print(caloriesBurned)
def burnedWalks(user_weight):
caloriesBurned = user_weight * .054
print(caloriesBurned)
def timeRequiredRun(caloriesDaily, user_weight):
caloriesBurned = user_weight * .095
timeToRun = calories / caloriesBurned
print(timeToRun)
timeRequiredRun(caloriesBurned, user_weight)
Your last line timeRequiredRun(caloriesBurned, user_weight) uses a variable called caloriesBurned which does not exist. I think you are looking for something like this:
def CalorieBurn(user_weight, user_height, user_age):
calories = 655 + (4.3 * user_weight) + (4.7 * user_height) - (4.7 * user_age)
return calories
def timeRequiredRun(calories, user_weight):
caloriesBurned = user_weight * .095
timeToRun = calories / caloriesBurned
print(timeToRun)
calories = CalorieBurn(weight, height, age)
timeRequiredRun(calories, user_weight)
You have defined caloriesBurned inside a function. This means it is only in that local scope and you cannot call it outside that function. You can use the return keyword to return that variable at the end of the function if you want, like return caloriesBurned. If you then set a variable as the function eg var = func() and the function had return caloriesBurned at the end then it will now be equal to the variable.
It appears that you have perhaps used the wrong variable in your call to timeRequiredRun(caloriesBurned, user_weight). Maybe you have forgotten to ask the user how many calories they consume per day?

Python raw input function for tax calculation

I am trying to make a simple calculator for working out the tax due on a salary. Please see the code below:
I keep getting this error and I don't know what is wrong, please help :) thanks!
Traceback (most recent call last):
File "python", line 13
elif salary > 11000 and salary < 43000:
^
SyntaxError: invalid syntax
CODE:
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
salary >= 0
while true:
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
return tax
Steps to correct your code
step1 : the salary data type should be of int, to correct..use the following code
step 2: Indentation is compulsory in python, so indent your code very well
step 3: Add an else statement after the conditional statements
step 4: indent return statement
change your code to this one
salary = int(raw_input ("What is your salary?"))
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
salary >= 0
while true:
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
else :
tax = undefined
return tax
It felt like there was a better way of doing this, so I came up with an alternative route:
tax_bands = [11000, 43000, 150000]
tax_amts = [0.2, 0.4, 0.45]
salary = 43001
Placing the thresholds and amounts into a list means that you can change them more easily if you need to.
The function below creates a list of the tax calculations, tax_list, and then a separate list of the maximum tax liability in each band called max_tax (the upper band has no maximum).
It then compares the values in the lists, and overwrites the tax_list if the corresponding value is larger than the maximum.
Then it calculates the sum of all values in tax_list greater than zero and returns it.
def taxes(salary, tax_bands, tax_amts):
tax_list = [(pct * (salary - band)) for (band, pct) in zip(tax_bands, tax_amts)]
max_tax = []
for index, sal in enumerate(tax_bands[:-1]):
max_tax.append(tax_bands[index + 1] - sal)
max_tax = [segment * tax for segment, tax in zip(max_tax, tax_amts[:-1])]
for index, value in enumerate(tax_list):
try:
if value > max_tax[index]:
tax_list[index] = max_tax[index]
except:
pass
tax_to_pay = sum([x for x in tax_list if x > 0])
return tax_to_pay
print taxes(salary, tax_bands, tax_amts)
salary = input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nYour net annual salary is: {} GBP".format(salary - taxes(salary, tax_bands, tax_amts))
To be super safe, you could also have the first line in the function call int(salary) using a try except just to check that it's the right type and that someone hasn't entered 43,000.
That because there are indent error in line number 12, now you can just copy pust this :
note : salary > 11000 and salary < 43000 equivalent to 11000 < salary < 43000 in python:
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
while true:
if salary < 11000:
tax = 0
elif 11000 < salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
return tax
As the comments have already stated, your indentation is incorrect. See below:
def taxes(salary):
salary >= 0
tax = 0
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
print("Value of tax is: " + str(tax))
return tax
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
print("\nHere is your net salary after taxes: %r" % (taxes(int(salary))))
With python, indentations are how you tell the interpreter which blocks of code fall where (unlike with Java for example with semicolons being the end of line delimiter). By not indenting properly on your elif statements, you are essentially telling the program there is an elif without an if hence your syntax problem.

net gain/loss in python

I'm doing a project where I need to figure if my transactions will earn me a profit or hit me for a loss. It's based on buying and selling stocks with commission. I got the basic math concept all worked out. What I am struggling with is the last equation where I subtract the sale price from the purchase price. I need a statement (or two) that if the answer is positive, it will go to output saying I gained x amount of money. If the answer is negative, it will go to output saying I lost x amount of money.
What statements could I use where the Python program will know to send positive number to gain output and negative number to loss output?
Here's the code I wrote with your suggestion for if statement
number_of_shares = input("Enter number of shares: ")
purchase_price = input("Enter purchase price: ")
sale_price = input("Enter sale price: ")
price = number_of_shares * purchase_price
first_commission = price * .03
final_price = price - first_commission
sale = number_of_shares * sale_price
second_commission = sale * .03
last_price = sale - second_commission
net = final_price - last_price
if (net > 0):
print("After the transaction, you gained", net, "dollars.")
if (net < 0):
print("After the transaction, you lost", net, "dollars.")
I didn't realize I was putting the loss as a gain and vice versa so I swapped it around and changed the wording to make it more clear. I'm still stuck here's my updated code
number_of_shares = input("Enter number of shares: ")
purchase_price = input("Enter purchase price: ")
sale_price = input("Enter sale price: ")
price = number_of_shares * purchase_price
first_commission = price * .03
buy_price = price - first_commission
sale = number_of_shares * sale_price
second_commission = sale * .03
sell_price = sale - second_commission
net = sell_price - buy_price
if net > 0:
print("After the transaction, you gained", net, "dollars.")
if net < 0:
print("After the transaction, you lost", net, "dollars.")
After doing the code on paper, I saw my mistake (with the commission) and made changes. Now my issue is when the net is for a loss, the output gives me an negative number. How do i make it not negative? since I already have the statement- you lost x dollars. Hmm multiplying by negative 1? Here's what I did
number_of_shares = int(input("Enter number of shares: "))
purchase_price = float(input("Enter purchase price: "))
sale_price = float(input("Enter sale price: "))
buy = float(number_of_shares * purchase_price)
first_commission = float(buy * .03)
sale = float(number_of_shares * sale_price)
second_commission = float(sale * .03)
net = float(sale - buy - first_commission - second_commission)
if net > 0:
print("After the transaction, you gained", net, "dollars.")
if net < 0:
print("After the transaction, you lost", net * -1, "dollars.")
Without seeing the code you have so far it's a bit hard to give you help, but I'll try anyways.
It sounds like you're looking for an if statement. The following will probably do what you want:
# Assuming total_money is the output of everything before
# positive number is gain, negative is loss
if total_money > 0:
print 'You gained ${}'.format(total_money)
else:
print 'You lost ${}'.format(total_money)
This is part of a concept called flow control. To learn more about it, you can look at https://docs.python.org/2/tutorial/controlflow.html
Try the following format:
net_change = sell_price - buy_price - commission
if (net_change >0):
print('Money! Money in the bank!\nYou have made $'+str(net_change))
else if (net_change <0):
print('Oh, sad deleterious day!\nYou have lost $'+str(net_change))
else:
print('You did not accomplish anything. You have broken even.')
This is a flow control path for three outcomes, Positive, Negative, and Neutral.
You'll find that flow control such as this is key to creating robust programs, it prevents the program from going to a place that it shouldn't.
Here is the code that worked
number_of_shares = int(input("Enter number of shares:"))
purchase_price = float(input("Enter purchase price:"))
sale_price = float(input("Enter sale price:"))
buy = float(number_of_shares * purchase_price)
first_commission = float(buy * .03)
sale = float(number_of_shares * sale_price)
second_commission = float(sale * .03)
net = float(sale - buy - first_commission - second_commission)
if net > 0:
print("After the transaction, you gained", net, "dollars.")
if net < 0:
print("After the transaction, you lost", net * -1, "dollars.")

Categories

Resources