Another Python NameError: name is not defined [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am having issues with a defined name error message in Python. I know there are quite a few responses to this question, but I cannot seem to find one that fits my situation. My code is as follows:
#Gets the input of the property value from the user and calculates the individual and total revenue
def main():
class_A_input = int(input('Please enter the number of Class A seats sold: '))
class_B_input = int(input('Please enter the number of Class B seats sold: '))
class_C_input = int(input('Please enter the number of Class C seats sold: '))
#Declares the cost for each class of ticket
class_A_cost = 20
class_B_cost = 15
class_C_cost = 10
#Passes the variable for each ticket class
class_A(class_A_input, class_A_cost)
class_B(class_B_input, class_B_cost)
class_C(class_C_input, class_C_cost)
#Calculates the total revenue
total_revenue = (class_A_input * class_A_cost) + ,\
(class_B_input * class_B_cost) + (class_C_input * class_C_cost)
print ('Total tickets revenue is $',format(total_revenue,',d'),sep='')
#Calculates the class A revenue
def class_A(A_input, A_cost):
class_A_revenue = A_input * A_cost
print ('The amount of Class A revenue is $',format(class_A_revenue,',d'),sep='')
#Repeat definitions for Class B and Class C
main()
I am running Python 3.6.0 and I am getting the following name error:
total_revenue = (class_A_input * class_A_cost) + ,\
(class_B_input * class_B_cost) + (class_C_input * class_C_cost)
NameError: name 'class_A_input' is not defined
I don't think I am declaring the variable before I use it. I have tried a variety of different solutions with no success. So what am I doing wrong?

This looks like an indentation issue. total_revenue is global and trying to use local variable from main() in its calculation.
p.s. You should learn about functions in order to help you reduce duplication in your code.

Related

Python error "netpay not defined" in functions [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
i keep getting the error above, my guess is that i'm not passing the info correctly
BASE_PAY=900
total_sale=float(input('What\'s your total sale?: '))
def main():
demographics=get_info()
income=get_income()
budget=get_budget(netpay)
print('Total sales is: $',total_sale)
print('Your comission is: $',comission)
print('The gross pay is: $',Gpay)
print('The deductions are: $',deductions)
print('The netpay is: $',netpay)
print('Housing & Utility: $', HnC)
print('Food & Clothing: $', FnC)
print('Entertainment: $', entertainment)
print('Miscellaneous costs: $', misc)
def get_info():
Fname=input('Enter your first name: ')
Lname=input('Enter your last name: ')
gender=input('Please enter your gender(m/f): ')
if gender=='m' or gender =='M':
print('Mr.',Fname,Lname)
else:
print('Ms.',Fname,Lname)
return Fname, Lname, gender
def get_income():
comission=total_sale*0.06
Gpay=BASE_PAY*comission
deductions=Gpay*0.18
netpay=Gpay-deductions
return comission, Gpay, deductions, netpay
def get_budget(netpay):
HnC=netpay*0.45
FnC=netpay*0.20
entertainment=netpay*0.25
misc=netpay*0.10
return Hnc,FnC, entertainment, misc
main()
You have not defined netpay for your function get_budget, you have defined it inside of another function locally get_income and so where you are trying to call it, it cannot be seen. You should create a global variable called netpay and declare it as None. Then you can edit it from inside your get_income function and call it in your get_budget function without returning this error.
Maybe have a read through this to gain an understanding of variable scope in python. https://www.w3schools.com/python/python_scope.asp

Python: "IndentationError: unindent does not match any outer indentation level" tried to troubleshoot but doesn't work [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
When I run my code even though I see nothing wrong
Please help
def savings_tracker():
input("This program will tracker your savings progress. (Press Enter to Continue)")
goal = input("What are you trying to save for?")
final_savings_amount = float(input("What is the total amount of money needed to each your goal"))
monthly_savings = float (input("What is your monthly savings?"))
current_savings = float(input("What have you saved so far?"))
month_to_reach_goal = (final_savings_amount-current_savings)/monthly_savings
month_to_reach_goal = math.ceil(month_to_reach_goal)
print("The time it will take to get to your goal of", goal, "is", month_to_reach_goal, "months!")
print("Your getting there! Keep on saving!")
I believe this will work for you:
import math
def savings_tracker():
input("This program will tracker your savings progress. (Press Enter to Continue)")
goal = input("What are you trying to save for? ")
final_savings_amount = float(input("What is the total amount of money needed to each your goal "))
monthly_savings = float (input("What is your monthly savings ?"))
current_savings = float(input("What have you saved so far? "))
month_to_reach_goal = (final_savings_amount-current_savings)/monthly_savings
month_to_reach_goal = math.ceil(month_to_reach_goal)
print(f"The time it will take to get to your goal of {goal} is {month_to_reach_goal} months!")
print("You're getting there! Keep on saving!")
savings_tracker()
Input:
This program will tracker your savings progress. (Press Enter to Continue)
What are you trying to save for? a house
What is the total amount of money needed to each your goal 250000
What is your monthly savings? 6000
What have you saved so far? 50000
Output:
The time it will take to get to your goal of a house is 34 months!
You're getting there! Keep on saving!
It is common practice to use 4 spaces for indentation. See official recommendation (PEP 8).
That should give you something like :
def savings_tracker():
input("This program will tracker your savings progress. (Press Enter to Continue)")
goal = input("What are you trying to save for?")
final_savings_amount = float(input("What is the total amount of money needed to each your goal"))
monthly_savings = float (input("What is your monthly savings?"))
current_savings = float(input("What have you saved so far?"))
month_to_reach_goal = (final_savings_amount-current_savings)/monthly_savings
month_to_reach_goal = math.ceil(month_to_reach_goal)
print("The time it will take to get to your goal of", goal, "is", month_to_reach_goal, "months!")
print("Your getting there! Keep on saving!")
Please consider a minimal example next time since this code is quite irrelevant to this particular indentation problem.

Why isn't this extracting the price correctly? Every price comes out to 0? Also it said 'payment' was being referenced before it was defined? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
# Sample line of text from file (Ford,F150,55000;)
filename = 'carPrice.txt'
def main():
all_prices= {}
try:
with open(filename) as fh:
for line in fh:
make, model, price = line.strip().split(',')
all_prices[(make,model)]=price.strip()
income = float(input("Enter your monthly income amount:"))
print("Your monthly income amount is",income,)
make = input("Enter Make of the car:")
print("You selected a",make,)
model = input("Enter Model of the car:")
print("You selected a",model,)
price_value=0
for x in price:
if x == (make,model):
price_value=price[x]
print("The price of that car is",price_value,)
payment = (price_value* 0.80)/60
print("The monthly payment is",payment,)
if (payment < 0.11*income):
print("The monthly payment of",payment,"= Acceptable Risk")
return "Acceptable"
else:
print("The monthly payment of",payment,"= Unacceptable Risk")
return "Unacceptable"
# Exception added to enable troubleshooting of errors on lines
except OSError as e:
print(e.errno)
if __name__ == '__main__':
main()
With respect, the code seems to be a bit all over the place, specifically in regards to price. If this is an exact copy of your code I think you may have lost track of what 'price' actually is.
For example here:
for x in price:
if x == (make,model):
price_value=price[x]
However, price here is a string value you pulled from the file e.g. £100. You're then iterating over that £, 1, 0, 0 and checking it against the make and model.
Finally you make the price_value an index of this string e.g.
price[x] # could be price["£"]
This would then cause an exception.
I'd go through your code again and look to make sure you're referencing price, price_value and all_prices where you actually want them

Whats wrong with my python program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
tip and tax calculator
bill = price + tax + tip
price = raw_input("What is the price of the meal")
tax = price * .06
tip = price * 0.20
what is wrong with my code
I have tried everything
please answer and get back to me
a few things.
bill = price + tax + tip #You can't add up these values BEFORE calculating them
price = raw_input("What is the price of the meal") #raw_input returns a string, not a float which you will need for processing
tax = price * .06 #So here you need to do float(price) * .06
tip = price * 0.20 #And float(price) here as well.
#Then your " bill = price + tax + tip " step goes here
First of all, you can't use variables that you haven't defined: in your code your are using bill = price + tax + tip but your program doesn't even know what price, tax and tip are yet, so that line should be at the end of the code, after you've asked the price and calculated tax and tip.
Then, you have raw_input, this function returns a string, if you want to convert it to a decimal number that you can multiply and add (float) you can use price = float(raw_input("what is the price of the meal"))
Correct that two things and it should work...
Heres a couple of things wrong with the code:
You're trying to calculate the total before some variables have been defined.
The raw_input function returns a string so you can't do proper mathematical calculations before you coerce it into an integer.
In calculate the tips/tax you should use a float with the whole number 1(1.20) to take the whole value of the bill + 20%.
Below is a code snippet that should work how you want and give you something to think about on how to pass dynamic values into the modifiers within the calculate_bill function for custom tip floats and custom tax floats:
def calculate_bill(bill, bill_modifiers):
for modifier in bill_modifiers:
bill = modifier(bill)
return bill
def calculate_tip(bill, percentage=1.20):
return bill * percentage
def calculate_tax(bill, percentage=1.06):
return bill * percentage
if __name__ == '__main__':
bill = int(input("What is the price of the meal: "))
total_bill = calculate_bill(bill, [calculate_tip, calculate_tax])
print(total_bill)

python oop classes, syntax error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
The following is giving me a syntax error at (def__init__(self, price, max_speed, total_miles_ridden, initial_miles = 0):)
I'm also wondering if I can concatenate like this: self.total_miles_ridden + 10?
^:
class Bike(object):
def__init__(self, price, max_speed, total_miles_ridden, initial_miles = 0):
self.price = price
self.max_speed = max_speed
self.total_miles_ridden = total_miles_ridden
self.initial_miles = initial_miles
def displayinfo(self):
print("The price is ", self.price)
print("This bike's max speed is ", self.max_speed)
print("The total miles is ", self.total_miles_ridden)
def ride(self):
print("Riding ", self.total_miles_ridden + 10) #add 10miles to total
def reverse(self):
print("Reversing " self.total_miles_ridden - 5) #minus 5 miles from total
bike1 = new Bike(200, '25mph')
print bike1
I think you're missing a space between def and init.

Categories