How do I fix this syntax error? I am confused - python

Here is all my coding that I did but I keep getting this syntax error. It will be explained more at the bottom.
def main():
ActualValue()
AssessedValue()
printResult()
def ActualValue()
global actual_value
actual_value = float(input("Enter actual value:\t"))
def AssessedValue()
global assessed_value
global property_tax
assessed_value = 0.6 * actual_value
property_tax = assessed_value / 100 * 0.64
def printResult():
print "n\For a property valued at $", actual_value
print "The assessed value is $", assessed_value
print "The property tax is $", property_tax
actual_value = None
assessed_value = None
property_tax = None
main()
That is my code:
It keeps saying that I have a syntax error:
def printResult():
print "n\For a property valued at $", actual_value
print "The assessed value is $", assessed_value
print "The property tax is $", property_tax

You have the \n escape sequence backwards.
Also, you need to make sure all your function definitions have a colon on the end of the line.
Also, print is a function in Python 3.

print is a function in Python 3:
def printResult():
print("\nFor a property valued at $", actual_value)
print("The assessed value is $", assessed_value)
print("The property tax is $", property_tax)
I fixed your \n newline escape code for you as well.
You probably want to use the .format() method to format your output:
def printResult():
print("\nFor a property valued at ${0}".format(actual_value))
print("The assessed value is ${0}".format(assessed_value))
print("The property tax is ${0}".format(property_tax))

Just to clarify what Platinum Azure said.
def main():
actualValue()
assessedValue()
printResult()
def actualValue():
global actual_value
actual_value = float(input("Enter actual value:\t"))
def assessedValue():
global assessed_value
global property_tax
assessed_value = 0.6 * actual_value
property_tax = assessed_value / 100 * 0.64
def printResult():
print "\nFor a property valued at $", actual_value
print "The assessed value is $", assessed_value
print "The property tax is $", property_tax
actual_value = None
assessed_value = None
property_tax = None
main()
This should work

Related

not sure what exactly is wrong

I am new at python, probably as new as it gets. I am working on a simple python code for mpg and refactoring. I am not sure exactly what I am doing wrong. Its giving me a error on line 65, "in goodbye print("your miles per gallon:", mpg) name error name 'mpg' is not defined. any help would be appreciated.
def main():
miles_driven = 0.0
gallons_of_gas_used = 0.0
mpg = 0.0
print_welcome()
print_encouragement()
goodbye()
# imput
miles_driven = your_miles_driven()
gallons_of_gas_used = gas_used()
# Calculation
mpg = your_mpg(miles_driven, gallons_of_gas_used)
print("Your miles per gallon:", mpg)
print("\nThanks for using my mpg calculator, I will be adding additional "
"functions soon!")
def print_welcome():
print("Welcome to Ray's trip calculator!\n")
def print_encouragement():
print("Let's figure out your miles per gallon!")
def your_miles_driven():
your_miles_driven = 0.0
your_miles_driven = float(input("Enter number of miles driven:"))
return your_miles_driven
def gas_used():
gas_used = 0.0
gas_used = float(input("Enter the gallons of gas you used:"))
return gas_used
def your_mpg(your_miles_driven, gas_used):
mpg = 0.0
your_mpg = your_miles_driven / gas_used
return your_mpg
def goodbye():
print("\nThanks for using my mpg calculator, I will be adding additional "
"functions soon!")
print("Your miles per gallon:" , mpg)
main()
Your code has 2 problems.
the goodbye function needs to receive mpg as an argument
you need to do the inputs before calling goodbye(), and pass the function the mpg
the following lines of code should be before calling goodbye().
# input
miles_driven = your_miles_driven()
gallons_of_gas_used = gas_used()
Your code should look like this:
def main():
print_welcome()
print_encouragement()
# input before goodbye()
# input
miles_driven = your_miles_driven()
gallons_of_gas_used = gas_used()
# after input calc the mpg
# Calculation
mpg = your_mpg(miles_driven, gallons_of_gas_used)
# and then call the goodbye function and pass mpg
goodbye(mpg)
def print_welcome():
print("Welcome to Ray's trip calculator!\n")
def print_encouragement():
print("Let's figure out your miles per gallon!")
def your_miles_driven():
your_miles_driven = float(input("Enter number of miles driven:"))
return your_miles_driven
def gas_used():
gas_used = float(input("Enter the gallons of gas you used:"))
return gas_used
def your_mpg(your_miles_driven, gas_used):
your_mpg = your_miles_driven / gas_used
return your_mpg
# goodbye function also needs to receive mpg
def goodbye(mpg):
print("Your miles per gallon:", mpg)
print("\nThanks for using my mpg calculator, I will be adding additional functions soon!")
if __name__ == '__main__':
main()
mpg is defined in your main function and is not passed to your goodbye function. If you add it as a parameter, it becomes available in that function with whatever value is passed as an argument:
def goodbye(mpg):
print("\nThanks for using my mpg calculator, I will be adding additional "
"functions soon!")
print("Your miles per gallon:" , mpg)
Now in your main function you can do:
mpg = your_mpg(miles_driven, gallons_of_gas_used)
goodbye(mpg)
and goodbye() will receive the value of mpg that was returned by your_mpg().

Python asking for input twice when I need it one time

Write a program that will ask the user for the cost of a meal, compute the tip for the meal (18%), compute the tax on the meal (8.25%), and then displays the cost of the meal, the tip amount for the meal, the tax on the meal, and the total of the meal which is a sum of the cost, tip, and tax amount
Here is my code:
def get_cost():
meal = float(input('Enter cost of meal: '))
while meal < 0:
print('Not possible.')
meal = float(input('Enter cost of meal: '))
return meal
def compute_tip():
tip = get_cost()*.18
return tip
def compute_tax():
tax = get_cost()*.0825
return tax
def compute_grand_total():
total = get_cost() + compute_tip() + compute_tax()
return total
def display_total_cost():
meal1 = print('Cost:', format(get_cost(), '.2f'))
tip3 = print('Tip:', format(compute_tip(), '.2f'))
tax3 = print('Tax:', format(compute_tax(), '.2f'))
total2 = print('Total:', format(compute_grand_total(), '.2f'))
return meal1, tip3, tax3, total2
def main():
m, t, ta, to = display_total_cost()
print('Cost:' , format(m, '.2f'))
print('Tip:', format(t, '.2f'))
print('Tax:', format(ta, '.2f'))
print('Total:', format(to, '.2f'))
main()
Output on Python Shell:
Enter cost of meal: 19.95
Cost: 19.95
Enter cost of meal: 19.95
Tip: 3.59
Enter cost of meal: 19.95
Tax: 1.65
Enter cost of meal: 19.95
This may be a very simple fix but how can I fix this where it doesn't ask for meal again? I'm still starting out.
Call get_cost() once and assign it to a variable; then pass that as a parameter to the other functions.
def compute_tip(meal):
return meal * .18
def compute_tax(meal):
return meal * .0825
def display_total_cost():
meal = get_cost()
return meal, compute_tip(meal), compute_tax(meal), compute_grand_total(meal)
You are calling get_cost() over and over again internally and that's why you are unable to find where the problem is. See you call it only once in the display_total_cost function but you are calling some other functions like compute_tip,compute_tax and compute_grand_total where all of them are internally calling the get_cost() function and that's why the programme asks you for multiple inputs.
Now, as suggested by everyone else you can store the return value in a variable and then pass it to all the other functions as an argument.
You also have a trivial main function in your programme which does the same thing as the display_total_cost function.
meal1 = print('Cost:', format(get_cost(), '.2f')) this is not the correct syntax.You can not use print statement after the assignment operator i.e. = Even though it won't raise any errors but why would you write extra things when you could just do a print statement cause using a print statement with assignment operator won't assign the variable with a value.
You also have another trivial function compute_grand_total you need not call functions again and again just to calculate previously calculated values unless and until you have a memory bound and you can not store values.
Fix it the following way:
def get_cost():
meal = float(input('Enter cost of meal: '))
while meal < 0:
print('Not possible.')
meal = float(input('Enter cost of meal: '))
return meal
def compute_tip(meal):
tip = meal*.18
return tip
def compute_tax(meal):
tax = meal*.0825
return tax
def display_total_cost():
meal = get_cost()
print('Cost:', format(get_cost(), '.2f'))
tip = compute_tip(meal)
print('Tip:', format(tip, '.2f'))
tax = compute_tax(meal)
print('Tax:', format(tax, '.2f'))
print('Total:', format(meal + tip + tax, '.2f'))
display_total_cost()

python unboundLocalError: local variable 'HighestStockName' referenced before assignment

I'm trying to write a program and am having a problem with one of my functions. When I try to run the program I get the following error about unboundLocalError. Can anyone help me with trying to fix this error?
def GetSale(Names, Prices, Exposure):
HighestStock = 0
for Stock in Names:
TotalProfit = ((Prices[Stock][1] - Prices[Stock][0]) - Exposure[Stock][1] *
Prices[Stock][0]) * Exposure[Stock][0]
if (TotalProfit > HighestStock):
HighestStock = TotalProfit
HighestStockName = Stock
print("Highest selling stock is", HighestStockName, "with a ", HighestStock, "profit margin.")
If the argument 'Names' is None or empty, or if the if (TotalProfit > HighestStock) condition is false...
print("Highest selling stock is", HighestStockName, "with a ", HighestStock, "profit margin.")
Will raise the UnboundLocalError because HighestStockName gets assigned within the if block of the for loop.
Perhaps try initializing the value 'HighestStockName' underneath HighestStock = 0 as such...
def GetSale(Names, Prices, Exposure):
HighestStock = 0
HighestStockName = ''
for Stock in Names:
TotalProfit = ((Prices[Stock][1] - Prices[Stock][0]) - Exposure[Stock][1] * Prices[Stock][0]) * Exposure[Stock][0]
if (TotalProfit > HighestStock):
HighestStock = TotalProfit
HighestStockName = Stock
print("Highest selling stock is", HighestStockName, "with a ", HighestStock, "profit margin.")
Or just catch the UnboundLocalError exception and figure out what to do from there...
def GetSale(Names, Prices, Exposure):
HighestStock = 0
for Stock in Names:
TotalProfit = ((Prices[Stock][1] - Prices[Stock][0]) - Exposure[Stock][1] * Prices[Stock][0]) * Exposure[Stock][0]
if (TotalProfit > HighestStock):
HighestStock = TotalProfit
HighestStockName = Stock
try:
print("Highest selling stock is", HighestStockName, "with a ", HighestStock, "profit margin.")
except UnboundLocalError, e:
# Do something after catching the exception
Consider that if all of the calculations of TotalProfit end up being 0 or negative, you never enter the inner if block, and therefore, the HighestStockName is never assigned/defined.

Getting a syntax error in Python and not sure why

I'm trying to create a program that asks for actual value of a piece of property and display the assessment value and property tax. The county collects property taxes on the assessment value of property, which is 60% of the property's actual value. The property tax is $.72 for each $100 of the assessment value.
Any suggestions on what I did wrong?
#Create a program that asks for th actual value of a piece of property
# and display tge assessnebt value and property tax.
ASSESSED_VALUE = .60
PROPERTY_TAX=.72 *(ASSESSED_VALUE/ 100.00)
def main():
property_value = float(input('Enter property value: '))
def calcu_value(property_value)
assessed_value = property_value *assessed_value
property_tax = property_value * property_tax
# display totals of
def display_calcu
print(property_value)
format ('total_sales tax, '.2f'))
print(property_tax)
format ('total_sales tax, '.2f'))
# Call the main function
main()
There are quite a few syntax problems. Simplifying a bit (and I'm just taking a quick run at this), try this:
#Create a program that asks for th actual value of a piece of property
# and display tge assessnebt value and property tax.
ASSESSED_VALUE = .60
PROPERTY_TAX=.72 *(ASSESSED_VALUE/ 100.00)
def main():
property_value = float(input('Enter property value: '))
assessed_value = property_value * ASSESSED_VALUE
property_tax = property_value * PROPERTY_TAX
print("Property value: {}".format(property_value))
print("Property tax: {}".format(property_tax))
print("Assessed value: {}".format(assessed_value))
# Call the main function
main()
That runs without errors, at least.

Calculations in module / While Loop / Transferring Variables

I'm very new to python and I'm stuck in some basic problems.
I can't seem to be able to put most of my calculations in a module. If I do, the results are not transferable and they will always show up as 0.0.
Once I'm able to put my calculations in a module, I can put the module inside a loop and ask the user if he wants to repeat the action.
This is my main issue too :: I want to "store" the output (displayResults) of each of the items (item number, price, etc) and print all of them once the loop is cancelled.
Thanks! I'm having a pretty difficult time trying to figure this out.
Here is my code:
#Mateo Marquez
#Oct. 8th, 2012
#P.O.S information system assigment
#
#Define Global Variables
TAX = 0.6
YELLOW_TAG = 0.10
BLUE_TAG = 0.20
RED_TAG = 0.25
GREEN_TAG = 0
#Main Module
def main():
tax_fee = 0.0
total_price = 0.0
introUser()
# I want this to be the mainCalc() function and return results.
productNumber=raw_input("Please enter the Product Number: ")
cost=float(raw_input("Please enter the cost of the selected product: "))
print " "
print "As you might have noticed, our discounts are color coded"
print "Yellow is 10%, Blue is 20% & Red is 25%"
print " "
tagDiscount=raw_input("Please enter the color tag: (yellow, blue, red or none)")
if tagDiscount == 'yellow':
print " "
print "You get a 10% discount"
total_price = (YELLOW_TAG*cost)
if tagDiscount == 'blue':
print " "
print "You get a 20% discount"
total_price = (BLUE_TAG*cost)
if tagDiscount == 'red':
print " "
print "You get a 25% discount"
total_price = (RED_TAG*cost)
if tagDiscount == 'none':
print " "
print "No discount for you!"
total_price = 0
print " "
print "~Remember~ this weekend is Tax Free in most of the country"
print "Green Tags designate if the product is tax free"
tagDiscount=raw_input("Does your product has a Green Tag? (yes or no)")
if tagDiscount == 'yes':
print " "
print "Good! your product is tax free"
tax_fee = 0
if tagDiscount == 'no':
print " "
print "I'm sorry, product", productNumber, "requires regular tax"
tax_fee = (TAX*total_price)
#I want this to be the end of the mainCalc() function
displayResults(total_price, tax_fee, cost, productNumber)
#Introduction function
def introUser():
print "Welcome to Wannabee's"
print "I'll gladly help you with your price question"
print "Let's start"
print " "
#Display results function
def displayResults(total_price, tax_fee, cost, productNumber):
print " "
print "Your Product Number: ", productNumber
print "Listed price of your product: $", cost
print "Your discount: $", total_price
print "Your Tax amount: $", tax_fee
print "Your grand total: $", (cost - total_price - tax_fee)
print " "
print "Your savings: ", ((cost-total_price)/cost*100),"%!"
main()
In order to save values used by related routines, put the variables and the routines that use them in a class. The following code defines a "POS" class and two method routines that share its variables. The "self." notation in the methods indicates a class variable that is saved in the instance "p" that is created when the class is instantiated with p = POS().
The example illustrates how the variables are stored; you'll need to adjust the inputs and print statements as needed (they're in Python 3 here). If you want to store the items as they are input and print them at the end, create an empty list in __init__, add a tuple to the list in mainCalc(), and print out each of the list items in displayResults().
class POS:
def __init__(self):
self.taxrate = 0.06
self.disc = {"": 0.0, "yellow": 0.10, "blue": 0.20, "red": 0.25}
self.total = 0
self.savings = 0
self.tax = 0
def mainCalc(self, item, qty, cost, tag, taxable):
print(qty, "* Item", item, "# ${:.2f}".format(cost),
"= ${:.2f}".format(qty*cost))
discount = cost * self.disc[tag]
if (tag):
print(" You get a", int(100*self.disc[tag]),
"% discount ${:.2f}".format(discount), "for", tag, "tag")
self.total += qty * (cost - discount)
self.savings += discount
if (taxable == "yes"):
tax = qty * cost * self.taxrate
self.tax += tax
print(" tax ${:.2f}".format(tax))
else:
print(" tax free")
def displayResults(self):
print("----------------")
print("Your total: ${:.2f}".format(self.total))
print("Your savings: ${:.2f}".format(self.savings))
print("Your total tax: ${:.2f}".format(self.tax))
print("Grand total: ${:.2f}".format(self.total + self.tax))
return
p = POS()
# Item Qty Price Tag Taxable
items = [(1492, 1, 1.95, "yellow", "yes"),
(1524, 2, 4.50, "blue", "no"),
(2843, 1, 6.95, "blue", "yes"),
(1824, 3, 2.29, "", "yes")]
for i in items:
p.mainCalc(*i)
p.displayResults()
Running the example produces:
1 * Item 1492 # $1.95 = $1.95
You get a 10 % discount $0.20 for yellow tag
tax $0.12
2 * Item 1524 # $4.50 = $9.00
You get a 20 % discount $0.90 for blue tag
tax free
1 * Item 2843 # $6.95 = $6.95
You get a 20 % discount $1.39 for blue tag
tax $0.42
3 * Item 1824 # $2.29 = $6.87
tax $0.41
----------------
Your total: $21.39
Your savings: $2.49
Your total tax: $0.95
Grand total: $22.33
You should consider the following constraints:
A function can only be called after it has been defined by a def statement (your call to displayResults.
Functions cannot access variables that are defined locally in the body of another function definition.
To improve your code, either think about how the program should flow from an overall point of view, or use a class as suggested in Dave's answer.

Categories