This code is giving me this error.
class Bank:
line 117, in Bank
main()
in main
format(z, '10.2f'), format(bank.MakeWithdrawal(self,amount)))
AttributeError: 'float' object has no attribute 'MakeWithdrawal'
Any idea where I'm going wrong?
Thanks in advance!!!!
class Bank:
def __init__(self,incomingAcctNum,incomingBalance):
self.__acctNum = incomingAcctNum
self.__balance = incomingBalance
self.__totalDeposits = 0
self.__DepositCount = 0
self.__totalWithdrawals = 0
self.__WithdrawalCount = 0
def MakeDeposit(self,amount):
self.__balance = self.__balance + amount
self.__totalDeposits = self.__totalDeposits + amount
self.__DepositCount = self.__DepositCount + 1
def MakeWithdrawal(self,amount):
if (self.__balance >= amount):
self.__balance = self.__balance - amount
self.__totalDeposits = self.__totalDeposits + amount
self.__DepositCount = self.__DepositCount + 1
return True
else:
return False
def DisplayBalance(self):
self.__balance = self.__balance
self.__totalDeposits = self.__totalDeposits
self.__DepositCount = self.__DepositCount
def getAcctNum(self):
return self.__acctNum
def getBalance(self):
return self.__balance
def getTotalDeposits(self):
return self.__totalDeposits
def getDepositCount(self):
return self.__DepositCount
def getTotalWithdrawals(self):
return self.__totalWithdrawals
def getWithdrawalCount(self):
return self.__WithdrawalCount
def main():
a = input("Enter bank account ID #1: ")
b = eval(input("Enter balance for bank account #1: "))
c = input("Enter bank account ID #2: ")
d = eval(input("Enter balance for bank account #2: "))
infile = open("trans","r")
x = (infile.readline().strip())
y = (infile.readline().strip())
z = eval(infile.readline())
print()
print(format("Acct", '15s'), format("Trans Type", '20s'),
format("Amount", '15s'), format("Balance", '10s'))
print("------------------------------------------------------------")
while x != "X":
bank = (z)
if y == "W":
print(format(x, '15s'), format("Withdrawal", '15s'),
format(z, '10.2f'), format(bank.MakeWithdrawal()))
elif y == "D":
print(format(x, '15s'), format("Deposit", '15s'),
format(z, '10.2f'), format(bank.MakeDeposit(self,amount)))
else:
print(format(x, '15s'), format("Balance", '25s'),
format(bank.DisplayBalance(self)))
x = (infile.readline().strip())
y = (infile.readline().strip())
z = eval(infile.readline())
print("-------------------------------------------------------------")
print()
print(format("ABC123, Deposits: ", '15s'))
print(format("ABC123, Withdrawals: ", '15s'))
print(format("ABC123, Ending Balance: ", '20s'))
print()
print(format("DEF456, Deposits: ", '15s'))
print(format("DEF456, Withdrawals: ", '15s'))
print(format("DEF456, Ending Balance: ", '20s'))
main()
Your bank in this case is a float, I don't think that is right.
bank.MakeWithdrawal() needs an amount to withdrawal. i.e bank.MakeWithdrawal(amount)
in
if y == "W":
print(format(x, '15s'), format("Withdrawal", '15s'),
format(z, '10.2f'), format(bank.MakeWithdrawal()))
The same goes for bank.Makedeposit(). bank.DisplayBalance() doesn't need an input bank is the self when called. i.e. bank.DisplayBalance()
Also make sure that your indentatation is correct, I don't know if it is a copy/paste error or not, but it looks like your def main() is a method in the Bank class.
You first say that z is a float by the line z = eval(infile.readline()).
Then you say that bank is z since bank = (z).
Make bank an instance of Bank instead, possibly in a main loop outside of the class.
create an object of Bank class and call bank methods on it replace line bank=(z) with bank=Bank(inComingAcctNum,incomingBalance) .
and also keep main out of the class.
Related
I have created a class to store the details of all the employees and display the same. But I have to display the sum of salary of all the employees. I am unable to do that. Can anyone help me......???
class Employee :
empid = 0
name = None
salary = 0.0
def getInput(self) :
print("Enter the empid :: ", end ="")
self.empid = input()
print("Enter the name :: ", end ="")
self.name = input()
print("Enter the salary :: ", end ="")
self.salary = input()
def display(self) :
print("Employee id = " + str(self.empid))
print("Employee name = " + self.name)
print("Employee salary = " + str(self.salary))
def main( args) :
e = [None] * (3)
i = 0
while (i < 3) :
e[i] = Employee()
e[i].getInput()
i += 1
print("**** Data Entered as below ****")
i = 0
while (i < 3) :
e[i].display()
i += 1
if __name__=="__main__":
Employee.main([])
How to print sum of salary of employees after storing them using this.???
First of all, you need to get main() out of your class. Then, you should actually add the code that calculate the sum of the salaries. sumsalary() isn't declared anywhere in your code, the reason that you are not getting an error, it's because the value of i is greater than 3, so that part isn't reachable.
I updated your code so that it calculates the sum without creating a function.
class Employee :
empid = 0
name = None
salary = 0.0
def getInput(self) :
print("Enter the empid :: ", end ="")
self.empid = input()
print("Enter the name :: ", end ="")
self.name = input()
print("Enter the salary :: ", end ="")
self.salary = input()
def display(self) :
print("Employee id = " + str(self.empid))
print("Employee name = " + self.name)
print("Employee salary = " + str(self.salary))
def main(args):
e = [None] * (3)
i = 0
while (i < 3) :
e[i] = Employee()
e[i].getInput()
i += 1
print("**** Data Entered as below ****")
i = 0
while (i < 3) :
e[i].display()
i += 1
i=0
sum_salary = 0
while(i<3):
sum_salary += int(e[i].salary)
i += 1
print("sum salary: " + str(sum_salary) )
if __name__=="__main__":
main([])
#this is my code that would add loaned and withdrawed but it seems like my code is wrong but it doesn't have
class Money:
loaned = 0
withdrawed = 0
totalMoney = 0
def bankMoney (self):
self.totalMoney = self.withdrawed + self.loaned
return totalMoney
if totalMoney >= 1000000:
print(" enough money,")
else:
print("not enough")
m1 = Money()
m1.loaned = float(input("loaned"))
m1.withdrawed = float(input("withdrawed"))
#then when I try to execute it. it just ask the user but doesn't solve
Remove the return statement if you want the print statements inside the method bankMoney, as statements after return are not executed.
Add self. to totalMoney at the if statement
Call the method m1.bankMoney to execute it
Try the following:
Code
class Money:
loaned = 0
withdrawed = 0
totalMoney = 0
def bankMoney (self):
self.totalMoney = self.withdrawed + self.loaned
if self.totalMoney >= 1000000:
print(" enough money,")
else:
print("not enough")
m1 = Money()
m1.loaned = float(input("loaned "))
m1.withdrawed = float(input("withdrawed "))
m1.bankMoney()
Output
loaned 1000000
withdrawed 1
enough money,
There are three issues:
the function is not executed
your return statement is not indented correctly
you can't return before print, then you won't be able to execute the print statement at all
try it:
class Money:
def __init__(self):
self.totalMoney = 1000000
self.loaned = float(input("loaned: "))
self.withdrawed = float(input("withdrawed: "))
def bankMoney (self):
total = self.withdrawed + self.loaned
if total >= self.totalMoney:
print(" enough money")
else:
print("not enough")
return total
m1 = Money()
m1.bankMoney()
Like this:
class Money():
def __init__(self,l, w):
self.loaned = l
self.withdrawed = w
self.totalMoney = 0
def bankMoney(self):
self.totalMoney = self.withdrawed + self.loaned
if self.totalMoney >= 1000000:
print("enough money,")
else:
print("not enough")
return self.totalMoney # this is returned at the end
loaned = float(input("loaned : "))
withdrawed = float(input("withdrawed: "))
m1 = Money(loaned, withdrawed)
print(m1.bankMoney()) # the method within the class is to be called.
Output:
loaned : 555.4444
withdrawed: 654654653545.89
enough money,
654654654101.3345
In the code below, I want the menu to display and prompt the user for a selection. Based on the selection, I want to move on to the following if statements which allow the user to define the attributes of their vehicle. The code worked before I put the menu in a function, but this format is required for my assignment. No errors. It simply prompts for a selection over and over again. Any suggestions?
class Menu:
""" Create a Menu """
def __init__(self):
self.selection = selection
def displayHomeMenu(self):
if 2 == vehicleCount:
print("----Press 1 for car ")
print("----Press 2 for pickup ")
selection = input("----Press 3 to quit ")
return selection
else:
print("----Press 1 for car ")
selection = input("----Press 2 for pickup ")
return selection
class Vehicle:
""" Model a vehicle"""
def __init__(self, make = " ", model = "n/a", color = "n/a ", fuelType = "n/a ", *options):
""" Initialize vehicle attributes """
self.make = make
self.model = model
self.color = color
self.fuelType = fuelType
self.options = {"power windows", "powerlocks", "remote start", "backup camera", "bluetooth", "cruise control", "heated seats", "heated steering wheel"}
def getMake(self):
self.make = input("Please enter your make ")
return self.make
def getModel(self):
self.model = input("Please enter your model ")
return self.model
def getColor(self):
self.color = input("Please enter the color ")
return self.color
def getFuelType(self):
self.fuelType = input("Please enter your fuel type ")
return self.fuelType
def getOptions(self):
print("Please select from the following options: ")
input(self.options)
return self.options
class Car(Vehicle):
"""Represents a car"""
def __init__(self, make = "n/a ", model = "n/a", color = "n/a ", fuelType = "n/a "):
super().__init__(make, model, color, fuelType)
""" Initialize car attributes"""
self.engineSize = " "
self.numDoors = " "
def getEngineSize(self):
self.engineSize = input("Please enter your engine size ")
return self.engineSize
def getNumDoors(self):
self.numDoors = input("How many doors do you have ")
return self.numDoors
class pickup(Vehicle):
"""Represents a pickup"""
def __init__(self, make = " ", model = " ", color = " ", fuelType = " "):
super().__init__(make, model, color, fuelType)
""" Initialize pickup attributes """
self.cabStyle = " "
self.bedLength = " "
def getCabStyle(self):
self.cabStyle = input("Please enter your cab style ")
def getBedLength(self):
self.bedLength = input("Please enter the length of your bed ")
i = 0
list = []
vehicleCount = 0
carCount = 0
pickupCount = 0
selection = 0
while True:
vehicleCount = pickupCount + carCount
m = Menu()
Menu.displayHomeMenu(m)
if selection == "1":
# Processing for item found
c = Car(Vehicle)
Vehicle.getMake(c)
Vehicle.getModel(c)
Vehicle.getColor(c)
Vehicle.getFuelType(c)
Car.getEngineSize(c)
Car.getNumDoors(c)
newcar = vars(c)
list.append(newcar)
if carCount < 1:
carCount = carCount + 1
else:
pass
elif selection == "2":
# Processing for item not found
p = pickup(Vehicle)
Vehicle.getMake(p)
Vehicle.getModel(p)
Vehicle.getColor(p)
Vehicle.getFuelType(p)
pickup.getCabStyle(p)
pickup.getBedLength(p)
newpickup = vars(p)
list.append(newpickup)
if pickupCount < 1:
pickupCount = pickupCount + 1
else:
for i in list:
print(i)
You are not using the return value from displayHomeMenu():
while True:
vehicleCount = pickupCount + carCount
m = Menu()
selection = m.displayHomeMenu() # Assign the return value to selection
if selection == "1":
# Processing for item found
c = Car(Vehicle)
Vehicle.getMake(c)
Vehicle.getModel(c)
Vehicle.getColor(c)
Vehicle.getFuelType(c)
Car.getEngineSize(c)
Car.getNumDoors(c)
newcar = vars(c)
list.append(newcar)
if carCount < 1:
carCount = carCount + 1
else:
pass
elif selection == "2":
# Processing for item not found
p = pickup(Vehicle)
Vehicle.getMake(p)
Vehicle.getModel(p)
Vehicle.getColor(p)
Vehicle.getFuelType(p)
pickup.getCabStyle(p)
pickup.getBedLength(p)
newpickup = vars(p)
list.append(newpickup)
if pickupCount < 1:
pickupCount = pickupCount + 1
else:
for i in list:
print(i)
I have an intro class in Python where part of the instructions are:
(2) Build the ShoppingCart class with the following data attributes and related methods. Note: Some can be method stubs (empty methods) initially, to be completed in later steps.
Parameterized constructor which takes the customer name and date as parameters
Attributes
customer_name (string) - Initialized in default constructor to "none"
current_date (string) - Initialized in default constructor to "January 1, 2016"
cart_items (list)
Methods
add_item()
Adds an item to cart_items list. Has parameter ItemToPurchase. Does not return anything.
The code is:
class ItemToPurchase:
def __init__(self):
self._name = "none"
self._price = 0
self._quantity = 0
self._description = "none"
def item_name(self, name):
self._name = name
def item_price(self, price):
self._price = price
def item_quantity(self, quantity):
self._quantity = quantity
def item_description(self, description):
self._description = description
def __str__(self):
print("For item " + self._name + ": " + self._description + " there are " + str(self._quantity) + " available at $" + str(self._price) + ".")
def print_item_cost(self):
print(self._name + " " + str(self._quantity) + " # $" + str(self._price) + " = $" + str(self._quantity * self._price))
def print_item_description(self):
print(self._name + ": " + self._description)
class ShoppingCart:
def __init__(self, name="none", date="January 1, 2016"):
cart_items = []
_customer_name = name
_current_date = date
def add_item(self, cartItem):
self.cart_items.append(cartItem)
def remove_item(self, item_name):
count = 0
itms = self.cart_items[:]
for i in range(len(itms)):
itm = itms[i]
if itm._name == item_name:
del self.cart_items[i]
count += 1
if count == 0:
print(" ")
print("Item not found in cart. Nothing removed.")
def modify_item(self, ItemToPurchase):
count = 0
itms = self.cart_items[:]
for i in range(len(itms)):
itm = itms[i]
if itm._name == ItemToPurchase._name:
count += 1
if ItemToPurchase._description != "none":
itm.item_description(ItemToPurchase._description)
if ItemToPurchase._price != 0:
itm.item_price(ItemToPurchase._price)
if ItemToPurchase._quantity != 0:
itm.item_quantity(ItemToPurchase._quantity)
if count == 0:
print(" ")
print("Item not found in cart. Nothing modified.")
def get_num_items_in_cart(self):
count = 0
itms = self.cart_items[:]
for i in range(len(itms)):
itm = itms[i]
count += itm._quantity
return count
def get_cost_of_cart(self):
cost = 0
itms = self.cart_items[:]
for i in range(len(itms)):
itm = itms[i]
cost += (itm._quantity * itm._price)
return cost
def print_total(self):
print(self._customer_name + "'s Shopping Cart - " + self._current_date)
count = len(self.cart_items)
if count == 0:
print(" ")
print("SHOPPING CART IS EMPTY")
return 0
print("Number of Items: " + str(count))
print(" ")
for itm in self.cart_items:
itm.print_item_cost()
total = self.get_cost_of_cart()
print("Total: $" + str(total))
def print_descriptions(self):
print(self._customer_name + "'s Shopping Cart - " + self._current_date)
print(" ")
print("Item Descriptions")
for itm in self.cart_itmes:
print(itm.item_name() + ": " + itm.item_description())
def print_menu(cart):
print(" ")
print("MENU")
print("a - Add item to cart")
print("r - Remove item from cart")
print("c - Change item quntity")
print("i - Output items' descriptions")
print("o - Output shopping cart")
print("q - Quit")
print(" ")
def main():
#Define Constants and variables
custName = ""
dateToday = ""
custName = input("Enter customer's name: ")
dateToday = input("Enter today's date: ")
print("Customer name: " + custName)
print("Today's date: " + dateToday)
myCart = ShoppingCart(custName,dateToday)
option = ""
while option != "q":
print_menu(myCart)
option = input("Choose an option: ").lower().strip()
if option == "o":
myCart.print_descriptions()
elif option == "a":
print("ADD ITEM TO CART")
itemName = input("Enter the item name: ")
itemDescr = input("Enter the item description: ")
itemPrice = int(input("Enter the item price: "))
itemQuantity = int(input("Enter the item quantity: "))
print(" ")
cartItem = ItemToPurchase()
cartItem.item_name(itemName)
cartItem.item_description(itemDescr)
cartItem.item_price(itemPrice)
cartItem.item_quantity(itemQuantity)
myCart.add_item(cartItem)
elif option == "r":
print("REMOVE ITEM FROM CART")
itemName = input("Enter name of item to remove: ")
myCart.remove_item(itemName)
elif option == "c":
print("CHANGE ITEM QUNATITY")
itemName = input("Enter the item name: ")
itemQuantity = int(input("Enter the new quantity: "))
changeItem = ItemToPurchase(itemName)
changeItem.item_quantity(itemQuantity)
myCart.modify_item(changeItem)
main()
I am getting the following error:
Enter customer's name: Rog
Enter today's date: Oct 20
Customer name: Rog
Today's date: Oct 20
MENU
a - Add item to cart
r - Remove item from cart
c - Change item quntity
i - Output items' descriptions
o - Output shopping cart
q - Quit
Choose an option: a
ADD ITEM TO CART
Enter the item name: Sketchers
Enter the item description: Black
Enter the item price: 120
Enter the item quantity: 2
Traceback (most recent call last): File
"C:\PythonWorkspace\Chapter9Assignment\src\onlineShoppingCart2.py",
line 176, in
main() File "C:\PythonWorkspace\Chapter9Assignment\src\onlineShoppingCart2.py",
line 163, in main
myCart.add_item(cartItem) File "C:\PythonWorkspace\Chapter9Assignment\src\onlineShoppingCart2.py",
line 44, in add_item
self.cart_items.append(cartItem) AttributeError: 'ShoppingCart' object has no attribute 'cart_items'
Can anyone tell me what I am doing incorrectly?
class ShoppingCart:
def __init__(self, name="none", date="January 1, 2016"):
cart_items = []
_customer_name = name
_current_date = date
These are all local variable. If you want them to be attributes of the instance, you have to explicitly refer to self:
class ShoppingCart:
def __init__(self, name="none", date="January 1, 2016"):
self.cart_items = []
self._customer_name = name
self._current_date = date
i cant tell what this error is telling me it says the error is on line 64 of this code if possible can you please check too see if my code has additional errors thnx so much guys i tried multiple things and couldn't get it to work.
Traceback (most recent call last):
File "C:\Users\AdamFeffer\triviacrack.py", line 93, in <module>
QnA2()
File "C:\Users\AdamFeffer\triviacrack.py", line 64, in QnA2
if uanswer == quest[whichq].rA:
TypeError: 'type' object is not subscriptable
import random
import time
# Flase = playerone true player 2
wt = False
score = 0
kg = True
kgt = True
playerov = False
class playerone(object):
def __init__(self, name, score, victory):
self.name = name
self.score = score
self.victory = victory
class playertwo(object):
def __init__(self, name, score, victory):
self.name = name
self.score = score
self.victory = victory
class quest(object):
def __init__(self, q, a1, a2, a3, a4, rA):
self.question = q
self.answer1 = a1
self.answer2 = a2
self.answer3 = a3
self.answer4 = a4
self.realanswer = rA
### Questions ###
q1 = quest("The largest artery in the human body helps carry blood from the heart throughout the body. What is it?","Aorta", "your mom haha lol", "Jugular","Borta", 1)
q2 = quest("In the year 1900 in the U.S. what were the most popular first names given to boy and girl babies?", "William and Elizabeth", "Joseph and Catherine", "John and Mary","George and Anne", 3)
q3 = quest("When did the Liberty Bell get its name?", "when it was made, in 1701", "when it rang on July 4, 1776", "in the 19th century, when it became a symbol of the abolition of slavery", " none of the above", 3)
#################
#questoin arrays
questions = [q1, q2, q3]
qt = ["science", "history", "sports", "entertainment", "art"]
def QnA():
global kg
global oneplayer
global score
global player
p = player
whichq = random.randint(0, 4)
print(questions[whichq].question)
print(questions[whichq].answer1 + " (1)")
print(questions[whichq].answer2 + " (2)")
print(questions[whichq].answer3 + " (3)")
print(questions[whichq].answer4 + " (4)")
uanswer = int(input("answer "))
if uanswer == quest[whichq].realanswer:
score = score + 1
print ("YA NEXT QUESTION")
else:
print(p + "you didn't get it right")
kg = False
def QnA2():
global kgt
global wt
whichq = random.randint(0, 4)
print(questions[whichq].question)
print(questions[whichq].answer1 + " (1)")
print(questions[whichq].answer2 + " (2)")
print(questions[whichq].answer3 + " (3)")
print(questions[whichq].answer4 + " (4)")
uanswer = int(input("answer "))
if uanswer == quest[whichq].rA:
if wt == false:
playerone.score = playerone.score + 1
else:
playertwo.score = playertwo.score + 1
if wt == True:
wt = False
else:
wt = True
def timer():
timer = 60
while timer > 0:
print (timer)
timer = timer - 1
time.sleep(1)
print ("times up!!")
oot = int(input("(1) one player sudden death or (2) 2 player: "))
if oot == 1:
oneplayer = True
player = input("player name: ")
while kg == True:
QnA()
print("sorry your score was " + (score) + "gg")
else:
playero = input("player 1 name: ")
playert = input("player 2 name: ")
playerone = playerone(playero, 0, False)
playertwo = playertwo(playert, 0, False)
while kgt == True:
QnA2()
solution
Line 64: if uanswer == questions[whichq].realanswer:
Whats wrong
You are attempting to use quest which is a class instead of the questions list. quest can not be subscripted with [] but questions can, because it is a list.
In addition, you are trying to use rA which is an argument to the __init__ function. You can not use this argument outside of __init__. Instead you need to use the member variable realanswer :)