Getting a syntax error in Python and not sure why - python

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.

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

loan calculator using class(OOP) not running in python

# Create a class called "Loan":
# Data fields in the Loan class include: Annual Interest Rate(Float),\
# Number of years of loan(Float), Loan Amount(Float), and Borrower's Name(string)
class Loan:
# Create the initializer or constructor for the class with the above data fields.
# Make the data fields private.
def __init__(self, annualInterestRate, numberOfYears, loanAmount, borrowerName):
self.__annualInterestRate=annualInterestRate
self.__numberOfYears=numberOfYears
self.__loanAmount=loanAmount
self.__borrowerName
# Create accessors (getter) for all the data fields:
def getannualInterestRate(self):
return self.__annualInterestRate
def getnumberOfYears(self):
return self.__numberOfYears
def getloanAmount(self):
return self.__loanAmount
def getborrowerName(self):
return self.__borrowerName
# Create mutators (setters) for all the data fields:
def setannualInterestRate(self):
self.__annualInterestRate=annualInterestRate
def setnumberOfYears(self):
self.__numberOfYears=numberOfYears
def setloanAmount(self):
self.__loanAmount=loanAmount
def setborrowerName(self):
self.borrowerName=borrowerName
# Create a class method: getMonthlyPayment -
def getMonthlyPayment(self,loanAmount, monthlyInterestRate, numberOfYears):
monthlyPayment = loanAmount * monthlyInterestRate / (1
- 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))
return monthlyPayment;
# Create a class method: getTotalPayment -
def getTotalPayment(self):
monthlyPayment = self.getMonthlyPayment(float(self.loanAmountVar.get()),
float(self.annualInterestRateVar.get()) / 1200,
int(self.numberOfYearsVar.get()))
self.monthlyPaymentVar.set(format(monthlyPayment, '10.2f'))
totalPayment = float(self.monthlyPaymentVar.get()) * 12 \
* int(self.numberOfYearsVar.get())
self.totalPaymentVar.set(format(totalPayment, '10.2f'))
def main():
loan1=Loan()
print(input(float("Enter yearly interest rate, for exmaple, 7.25: ", loan1.annualInterestRate())))
print(input(float("Enter number of years as an integer: ", loan1.getnumberOfYears())))
print(input(float("Enter loan amount, for example, 120000.95: ", loan1.getloanAmount())))
print(input(float("Enter a borrower's name: ", loan1.getborrowerName())))
print("The loan is for", loan1.getborrowerName())
print("The monthly payment is", loan1.getMonthlyPayment())
print("The total payment is", loan1.getTotalPayment())
print(input("Do you want to change the loan amount? Y for Yes OR Enter to Quit"))
print(input(float("Enter a new loan amount: ")))
print("The loan is for", loan1.getborrowerName())
print("The monthly payment is", loan1.getMonthlyPayment())
print("The total payment is", loan1.getTotalPayment())
main()
For some reason my program is not running. I'm trying to allow the user to change the loan amount and reprint the new loan information. I don't know what I'm doing wrong, and classes/OOP is new to me, so I'm struggling dearly as I've been doing procedural-only for the past year. I am aware that this is filled with numerous errors... but I have nowhere to begin. All the tutorials for classes online are extremely vague and theoretical, and do not broach specific examples/scenarios like the one I'm facing with.
Any help would be appreciated.
The error message generated by the interpreter is more than enough.
TypeError: __init__() takes exactly 5 arguments (1 given)
You need to pass whatever input you are taking from the user as arguments into the class constructor Loan(). The other methods are just for returning class variables, but all the initialization is done in your constructor.
Also, your constructor definition is wrong, correct this line :
self.__borrowerName=borrowerName

While Loop in function ( Python )

So I basically created my functions ( def main(), load(), calc(), and print().
But I do not know how I can allow the user to input the information as many times as he/she wants until they want to stop. Like I they input 5 times, it would also output 5 times. I have tried putting the while loop in the def main() function and the load function but it won't stop when I want it to. Can someone help? Thanks!
def load():
stock_name=input("Enter Stock Name:")
num_share=int(input("Enter Number of shares:"))
purchase=float(input("Enter Purchase Price:"))
selling_price=float(input("Enter selling price:"))
commission=float(input("Enter Commission:"))
return stock_name,num_share,purchase,selling_price,commission
def calc(num_share, purchase, selling_price, commission):
paid_stock = num_share * purchase
commission_purchase = paid_stock * commission
stock_sold = num_share * selling_price
commission_sale = stock_sold * commission
profit = (stock_sold - commission_sale) - ( paid_stock + commission_purchase)
return paid_stock, commission_purchase, stock_sold, commission_sale, profit
def Print(stock_name,paid_stock, commission_purchase, stock_sold, commission_sale, profit):
print("Stock Name:",stock_name)
print("Amount paid for the stock:\t$",format(paid_stock,'10,.2f'))
print("Commission paid on the purchase:$", format(commission_purchase,'10,.2f'))
print("Amount the stock sold for:\t$", format(stock_sold,'10,.2f'))
print("Commission paid on the sale:\t$", format(commission_sale,'10,.2f'))
print("Profit(or loss if negative):\t$", format(profit,'10,.2f'))
def main():
stock_name,num_share,purchase,selling_price,commission = load()
paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
main()
You have to give the user some kind of way to declare their wish to stop the input. A very simple way for your code would be to include the whole body of the main() function in a while loop:
response = "y"
while response == "y":
stock_name,num_share,purchase,selling_price,commission = load()
paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
response = input("Continue input? (y/n):")
an even simpler way would be two do the following....
while True:
<do body>
answer = input("press enter to quit ")
if not answer: break
alternatively
initialize a variable and avoid the inner if statement
sentinel = True
while sentinel:
<do body>
sentinel = input("Press enter to quit")
if enter is pressed sentinel is set to the empty str, which will evaluate to False ending the while loop.

How do I fix this syntax error? I am confused

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

Categories