# 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
Related
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()
#create an EMPLOYEE object to store the name, hours worked, and hourly wage by passing them into the constructor. Be sure that the constructor prints the employee name, hours worked, and hourly wage. Then invoke the method that will calculate the employee’s pay. **
After calculating the pay for an employee, add it to the list created in step #1 above(lstPay)(add only the pay).
my code:
# STEP 2
class Employee(object):
def __init__(self, Name="", Hours="", Wage=""):
self.employeeName = Name`enter code here`
self.employeeHoursWorked = int(Hours)
self.employeeHourlyWage = float(Wage)
def Name(self):
print("Employee Name: ", self.employeeName.title())
def HoursWorked(self):
print("Hours worked: ", self.employeeHoursWorked)
def Wage(self):
print("Hourly wage: ", self.employeeHourlyWage)
def getEmpname(self):
return self.employeeName.title()
def setEmpname(self, epName):
self.employeeName = epName
def Emppay(self): # will calculate the employee pay based on info provided
if self.employeeHoursWorked <= 40:
print("Employee Pay :", self.employeeHoursWorked * self.employeeHourlyWage)
else:
print("Employee Pay :",
((self.employeeHoursWorked - 40) * (self.employeeHourlyWage * 1.5)) + (self.employeeHourlyWage * 40))
Empname = property(getEmpname, setEmpname)
# STEP 3
print()
strEmpName = input("Enter Employee Name: ")
intHoursWorked = int(input("Enter hours worked: "))
fltHourlyWage = float(input("Enter hourly wage: "))
objEmployee = Employee(strEmpName, intHoursWorked, fltHourlyWage) # the object objEmployee
objEmployee.Name()
objEmployee.HoursWorked()
objEmployee.Wage()
objEmployee.Emppay()
Do you mean this:
employees= list()
while True:
print()
strEmpName = input("Enter Employee Name: ")
if strEmpName.strip() == '':
break
else:
intHoursWorked = int(input("Enter hours worked: "))
fltHourlyWage = float(input("Enter hourly wage: "))
objEmployee = Employee(strEmpName, intHoursWorked, fltHourlyWage) # the object objEmployee
objEmployee.Name()
objEmployee.HoursWorked()
objEmployee.Wage()
objEmployee.Emppay()
employees.append(objEmployee)
The code above, would ask for employees as long as a name is entered, that is not an empty string and would append the records to list employees.
I'm new to functions, so I'm not quite sure how or why this is happening and I do not know how t fix it. Can someone explain why this error keeps occuring?
def loan_payment(l):
loan = float(input("Please enter how much you expend monthly on loan payments:"))
return loan
def insurance_cost(i):
insurance = float(input("Please enter how much you expend monthly on insurance:"))
return insurance
def gas_cost(g):
gas = float(input("Please enter how much you expend monthly on gas:"))
return gas
def maitanence_cost(m):
maitanence = float(input("Please enter how much you expend monthly on maintanence:"))
return maitanence
def monthly_cost(l, i, g, m):
monthly_expenses = float(l + i + g + m)
print("You expend $"+format(monthly_expenses, '.2f')+" in a month.")
return float(monthly_expenses)
def yearly_cost(monthly_cost):
yearly_expenses = 12 * monthly_cost
print("At your current monthly expenses, in a year you will have paid $"+format(yearly_expenses, '.2f')+".")
return yearly_expenses
def main():
loan_payment(l)
insurance_cost(i)
gas_cost(g)
maitanence_cost(m)
monthly_cost(l, i, g, m)
yearly_cost(monthly_cost)
main()
This code returns the error:
line 24, in main
loan_payment(l) NameError: name 'l' is not defined
I think you may have gotten your wires a bit crossed on how python passes by assignment, you wouldn't be the first, and here's a great question to help, as well as how to assign values and defining methods. As best as I can tell, your main method should look more like:
def main():
l = user_in_loan_payment()
i = user_in_insurance_cost()
g = user_in_gas_cost()
m = user_in_maintanence_cost()
monthly_cost = calculate_monthly_cost(l, i, g, m)
yearly_cost = calculate_yearly_cost(monthly_cost)
I changed the method names to start with "calculate" or "user_in" to make it a little more readable.
That's exactly what the error says: l is not defined, like any other variable. If I get it right you are trying to enter values in first 4 functions and then use them in the next two functions for calculations.
If that's true, your code should be as following:
def loan_payment():
loan = float(input("Please enter how much you expend monthly on loan payments:"))
return loan
def insurance_cost():
insurance = float(input("Please enter how much you expend monthly on insurance:"))
return insurance
def gas_cost():
gas = float(input("Please enter how much you expend monthly on gas:"))
return gas
def maitanence_cost():
maitanence = float(input("Please enter how much you expend monthly on maintanence:"))
return maitanence
def monthly_cost(l, i, g, m):
monthly_expenses = float(l + i + g + m)
print("You expend $"+format(monthly_expenses, '.2f')+" in a month.")
return float(monthly_expenses)
def yearly_cost(monthly_cost):
yearly_expenses = 12 * monthly_cost
print("At your current monthly expenses, in a year you will have paid $"+format(yearly_expenses, '.2f')+".")
return yearly_expenses
def main():
l = loan_payment()
i = insurance_cost()
g = gas_cost()
m = maitanence_cost()
mc = monthly_cost(l, i, g, m)
yearly_cost(mc)
main()
I'm in Grade 11 Computer Science at my highschool, and I'm just starting out in Python. I'm supposed to make a function called computepay that will ask the user their name, their wage, and their hours that week and automatically calculate the total, including any overtime and not error out when an incorrect input is included. I made different functions for all the inputs, but when I plug it all into my computepay function it tells me this:
TypeError: float() argument must be a string or a number
def mainloop(): #Creating a loop so it doesn't error out.
response = input('Make another calculation?[y/n]') #inputing loop
if response == 'n': #creating input for n
return
if response == 'y':
computepay()
else:
print("\n")
print ("Incorrect input. .")
mainloop()
def getname():
name = input ("What's your name?") #input of name
def getwage():
wage = input ("Hello there! How much money do you make per hour?") #input
try:
float(wage) #Making it so it does not error out when a float
except:
print ("Bad Input")
getwage()
def gethours():
hours = input ("Thanks, how many hours have you worked this week?")
try:
float(hours) #Making it so it does not error out when a float
except:
print("Bad Input")
gethours()
def computepay():
name = getname()
wage = getwage()
hours = gethours()
if float(hours) > float(40):
newhours = float(hours) - float (40) #figuring out the amount of overtime hours the person has worked
newwage = float (wage) * float (1.5) #figuring out overtime pay
overtimepay = float (newwage) * float (newhours) #calculating overtime total
regularpay = (float(40) * float (wage)) + overtimepay #calculating regular and overtime total.
print (name,",you'll have made $",round(regularpay,2),"this week.")
else:
total = float(wage) * float(hours)
print (name,",you'll have made $",round (total,2),"this week.")
mainloop() #creating the loop.
#-------------------------------------------------------------------------------
computepay()
None of these functions are returning anything
name = getname()
wage = getwage()
hours = gethours()
So they all end up being None
Try this
def getname():
return input("What's your name?") # input of name
def getwage():
wage = input("Hello there! How much money do you make per hour?") # input
return float(wage)
def gethours():
hours = input("Thanks, how many hours have you worked this week?")
return float(hours)
What the error message is telling you is that somewhere (on the line number reported in the part of the error message that you didn't show us) you are calling float and giving it an argument (i.e. an input) that is neither a number, nor a string.
Can you track down where this is happening?
Hint: Any Python function which doesn't return anything (with the return keyword) implicitly returns None (which is neither a string nor a number).
I have the following code in python:
class TotalCost:
#constructor
def __init__(self, quantity, size):
self.__quantity=quantity
self.__size=size
self.__cost=0.0
self.__total=0.0
def DetermineCost(self):
#determine cost per unit
if self.__size=="A":
self.__cost=2.29
elif self.__size=="B":
self.__cost=3.50
elif self.__size=="C":
self.__cost=4.95
elif self.__size=="D":
self.__cost=7.00
elif self.__size=="E":
self.__cost=9.95
def DetermineTotal(self): #calculate total
self.__total= self.__cost * self.__quantity
def GetCost(self):
return self.__cost
def GetTotal(self):
return self.__total
def Menu(self):
print("----------------SIZES/PRICES----------------")
print(" Size A = $2.92")
print(" Size B = $3.50")
print(" Size C = $4.95")
print(" Size D = $7.00")
print(" Size E = $9.95")
print("--------------------------------------------")
def main():
again=""
print("Prices:")
while again!="no":
size=""
quantity=0
display="" #i put this variable only because it wont go without it and idk what else to do>.<
TotalCost.Menu(display)
while size!="A" and size!="B" and size!="C" and size!="D" and size!="E":
size=str(input("Which size? Please enter A,B,C,D, or E. : "))
quantity=int(input("How many of this size? : "))
while quantity<0:
quantity=int(input("How many of this size? : "))
Calc=TotalCost(size, quantity)
Calc.DetermineCost()
Calc.DetermineTotal()
print("--------------------------------------------")
print("Your order:")
print("Size: " , size)
print("Quantity: " , quantity)
print("Cost each: $" , Calc.GetCost()) print("Total cost: $", Calc.GetTotal())
main()
I receive the following error when I execute this code:
File "C:/Python33/halpmeanon.py", line 21, in DetermineTotal
self._total= self._cost * self.__quantity
TypeError: can't multiply sequence by non-int of type 'float'
Context
This program is supposed to ask for a letter(size) & quantity, determine cost per unit by given letter, and calculate/output total cost.
How can I resolve this error in my code?
You got the order of arguments the wrong way round in
Calc=TotalCost(size, quantity)
Your constructor is:
def __init__(self, quantity, size):
A great way to code so you can make sure that doesn't happen is to name your arguments when calling a method:
Instead of:
Calc=TotalCost(size, quantity)
Do this:
Calc=TotalCost(size=size, quantity=quantity) # or TotalCost(quantity=quantity, size=size)
That way you can give the arguments out of order and not have to worry about bugs like the one you encountered.