AttributeError: 'str' object has no attribute 'print_item_cost' - python-3.x

While running this code I am receiving the following error message:
Traceback (most recent call last):
File "main.py", line 33, in <module>
item.print_item_cost()
AttributeError: 'str' object has no attribute 'print_item_cost'
I have verified the attribute is defined in the object, so I am not clear why this error is being thrown.
class ItemToPurchase:
def __init__(self, name = 'none', price = 0, qty = 0):
self.name = name
self.price = price
self.qty = qty
def print_item_cost(self):
print('%s %d # $%d = $%d' % (self.name, self.qty, self.price, (self.price * self.qty)))
def calculate_subtotal(self):
return self.price * self.qty
if __name__ == "__main__":
i = 0
order_list = []
for i in range(2):
print('Item %d' % int(i + 1))
print('Enter the item name:')
input_name = input()
item = input_name
item = ItemToPurchase()
item.name = input_name
print('Enter the item price:')
item.price = int(input())
print('Enter the item quantity:')
item.qty = int(input())
order_list.append(input_name)
print('\nTOTAL COST')
total = 0
for item in order_list:
print(item, '\n')
item.print_item_cost()
total += item.calculate_subtotal()
print('\nTotal: $%d' % total)
The program input I am giving is:
Chocolate Chips
3
1
Bottled Water
1
10
Which should result in the following output:
Item 1
Enter the item name:
Enter the item price:
Enter the item quantity:
Item 2
Enter the item name:
Enter the item price:
Enter the item quantity:
TOTAL COST
Chocolate Chips 1 # $3 = $3
Bottled Water 10 # $1 = $10
Total: $13

You're appending a string, not the item object to the list
input_name = input()
...
order_list.append(input_name)
Then looping over that list, expecting it not to be strings...
I'd recommend cleaning up that section a little so that you actually call the constructor of the class
print('Enter the item name:')
input_name = input()
print('Enter the item price:')
price = int(input())
print('Enter the item quantity:')
qty = int(input())
order_list.append(ItemToPurchase(input_name, price, qty))

Related

Issues with updating an inventory in Python Code

I'm working on a program for a final in a class and I'm having some troubles with updating the created inventory. I've been able to get it to the point where I can do everything else in the code, but when I go to run the update section, nothing updates. I'd be really grateful for any help with this. All of my code is included below
class Automobile:
def __init__(self, make, model, year, color, mileage=0):
self._make = make
self._model = model
self._year = year
self._color = color
self._mileage = mileage
#classmethod
def make_vehicle(cls):
make = input('Enter vehicle make: ')
model = input('Enter vehicle model: ')
while True:
year = input('Enter vehicle year: ')
try:
year = int(year)
break
except ValueError:
print("Year must be a number", file=sys.stderr)
color = input('Enter vehicle color: ')
while True:
mileage = input('Enter vehicle mileage: ')
try:
mileage = int(mileage)
break
except ValueError:
print("Mileage must be an integer", file=sys.stderr)
return cls(make, model, year, color, mileage)
def add_Vehicle(self):
vehicle = Automobile.make_vehicle()
self.vehicles.append(vehicle)
def __str__(self):
return '\t'.join(str(x) for x in [self._make, self._model, self._year, self._color, self._mileage])
class Inventory:
def __init__(self):
self.vehicles = []
def add_vehicle(self):
vehicle = Automobile.make_vehicle()
self.vehicles.append(vehicle)
def viewInventory(self):
print('\t'.join(['','Make', 'Model','Year', 'Color', 'Mileage']))
for idx, vehicle in enumerate(self.vehicles) :
print(idx + 1, end='\t')
print(vehicle)
print("This is the Vehicle Inventory Program.")
inventory = Inventory()
while True:
print ("""
1.Add a Vehicle
2.Delete a Vehicle
3.View Inventory
4.Update Inventory
5.Export Inventory
6.Quit
""")
ans=input("What would you like to do? ")
if ans=="1":
#add a vehicle
inventory.add_vehicle()
elif ans=='2':
#delete a vehicle
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
item = int(input('Please enter the number associated with the vehicle to be removed: '))
if item - 1 > len(inventory.vehicles):
print('This is an invalid number')
else:
inventory.vehicles.remove(inventory.vehicles[item - 1])
print ()
print('This vehicle has been removed')
elif ans == '3':
#list all the vehicles
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
elif ans == '4':
#edit vehicle
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
item = int(input('Please enter the number associated with the vehicle to be updated: '))
if item - 1 > len(inventory.vehicles):
print('This is an invalid number')
else:
if Inventory().add_vehicle() == True :
inventory.vehicles.remove(inventory.vehicles[item - 1])
inventory.vehicles.insert(item - 1, Automobile)
print('This vehicle has been updated')
elif ans == '5':
#export inventory to file
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
f = open('vehicle_inventory.txt', 'w')
f.write('\t'.join(['Make', 'Model','Year', 'Color', 'Mileage']))
f.write('\n')
for vechicle in inventory.vehicles:
f.write('%s\n' %vechicle)
f.close()
print('The vehicle inventory has been exported to a file')
elif ans == '6':
#exit the loop
print('Thank you for utilizing the Vehicle Inventory Program. Have a nice day.')
break
else:
print('invalid')
As already mentioned in the comments, the if condition is wrong and also you are inserting the class Automobile. What you need probably is Automobile.make_vehicle(). So, update the code,
elif ans == '4':
#edit vehicle
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
item = int(input('Please enter the number associated with the vehicle to be updated: '))
if item - 1 > len(inventory.vehicles):
print('This is an invalid number')
else:
inventory.vehicles.remove(inventory.vehicles[item - 1])
inventory.vehicles.insert(item - 1, Automobile.make_vehicle())
print('This vehicle has been updated')

The position argument error and resolving it

I am trying to implement a shopping cart in python and have this code but the error is that when i am calling a print_menu function , the arguments are not correct.
class ItemToPurchase:
def __init__(self, item_name= 'none', item_price=0, item_quantity=0, item_description = 'none'):
self.item_name = item_name
self.item_price = item_price
self.item_quantity = item_quantity
self.item_description = item_description
def print_item_cost(self):
string = '{} {} # ${} = ${}'.format(self.item_name, self.item_quantity, self.item_price, (self.item_quantity* self.item_price))
cost = self.item_quantity * self.item_price
return string, cost
def print_item_description(self):
string = '{}: {}'.format(self.item_name, self.item_description)
print(string, end=' ')
return string
class ShoppingCart:
def __init__(self,customer_name= None ,current_date='January 1,2016',cart_items=[]):
self.customer_name = customer_name
self.current_date = current_date
self.cart_items = cart_items
def add_item(self):
print('\nADD ITEM TO CART', end='\n')
item_name = str(input('Enter the item name:'))
item_description = str(input('\nEnter the item description:'))
item_price = int(input('\nEnter the item price:'))
item_quantity = int(input('\nEnter the item quantity:\n'))
self.cart_items.append(ItemToPurchase(item_name, item_price, item_quantity, item_description))
def remove_item(self):
print()
print('REMOVE ITEM FROM CART', end='\n')
string = str(input('Enter name of item to remove:\n'))
i = 0
for item in self.cart_items:
if(item.item_name == string):
del self.cart_items[i]
i += 1
flag=True
break
else:
flag=False
if(flag==False):
print('Item not found in cart. Nothing removed.')
def modify_item(self):
print('\nCHANGE ITEM QUANTITY', end='\n')
name = str(input('Enter the item name:'))
for item in self.cart_items:
if(item.item_name == name):
quantity = int(input('Enter the new quantity:'))
item.item_quantity = quantity
flag=True
break
else:
flag=False
if(flag==False):
print('Item not found in cart. Nothing modified.')
def get_num_items_in_cart(self):
num_items = 0
for item in self.cart_items:
num_items += item.item_quantity
return num_items
def get_cost_of_cart(self):
total_cost = 0
cost = 0
for item in self.cart_items:
cost = (item.item_quantity * item.item_price)
total_cost += cost
return total_cost
def print_total(self):
total_cost = self.get_cost_of_cart()
if (total_cost == 0):
print('SHOPPING CART IS EMPTY')
else:
self.output_cart()
def print_descriptions(self):
print('OUTPUT ITEMS\' DESCRIPTIONS')
print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date),end='\n')
print('\nItem Descriptions', end='\n')
for item in self.cart_items:
print('{}: {}'.format(item.item_name, item.item_description), end='\n')
def output_cart(self):
new=ShoppingCart()
print('OUTPUT SHOPPING CART', end='\n')
print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date),end='\n')
print('Number of Items:', new.get_num_items_in_cart(), end='\n\n')
self.total_cost = self.get_cost_of_cart()
if (self.total_cost == 0):
print('SHOPPING CART IS EMPTY')
else:
pass
tc = 0
for item in self.cart_items:
print('{} {} # ${} = ${}'.format(item.item_name, item.item_quantity,
item.item_price, (item.item_quantity * item.item_price)), end='\n')
tc += (item.item_quantity * item.item_price)
print('\nTotal: ${}'.format(tc), end='\n')
def print_menu(ShoppingCart):
customer_Cart = newCart
string=' '
#declare the string menu
menu = ('\nMENU\n'
'a - Add item to cart\n'
'r - Remove item from cart\n'
'c - Change item quantity\n'
'i - Output items\' descriptions\n'
'o - Output shopping cart\n'
'q - Quit\n')
command = ''
#Using while loop
#to iterate until user enters q
while(command != 'q'):
string=''
print(menu, end='\n')
#Prompt the Command
command = input('Choose an option: ')
#repeat the loop until user enters a,i,r,c,q commands
while (command != 'a' and command != 'o' and command != 'i' and command != 'r' and command != 'c' and command != 'q'):
command = input('Choose an option: ')
#If the input command is a
if(command == 'a'):
#call the method to the add elements to the cart
customer_Cart.add_item(string)
#If the input command is o
if(command == 'o'):
#call the method to the display the elements in the cart
customer_Cart.output_cart()
#If the input command is i
if(command == 'i'):
#call the method to the display the elements in the cart
customer_Cart.print_descriptions()
#If the input command is i
if(command == 'r'):
customer_Cart.remove_item()
if(command == 'c'):
customer_Cart.modify_item()
if __name__ == "__main__":
customer_name = str(input('Enter customer\'s name:'))
current_date = str(input('\nEnter today\'s date:'))
print()
print()
print('Customer name:', customer_name, end='\n')
print('Today\'s date:', current_date, end='\n')
newCart = ShoppingCart(customer_name, current_date)
newCart.print_menu(newCart)
i have created an instance of class ShopppingCart but it is not working. i am trying to get a user input and then display the menu for user to choose and implement one of the functions defined in the shopping cart class . Can anyone help me with resolving this issue.
This issue is happening because of function's argument, ShoppingCart. You have called the first argument ShoppingCart, which in reality is the ShoppingCart object; usually this is the self argument. Python does not care what you name it: self, ShoppingCart, corona. The first argument will always be the object that called the function. When calling this function with these lines of code:
newCart = ShoppingCart(customer_name, current_date)
newCart.print_menu(newCart)
you are using the newCart object to call the function and then passing the newCart object as an argument. You don't need to do this. Python already passes the object, so you don't have to.
I'm assuming this is the error you received:
Traceback (most recent call last):
File "c:/Users/jeffg/Desktop/ProgrammingProjects/StackOverFlow/shoppingcart.py", line 246, in <module>
newCart.print_menu(newCart)
TypeError: print_menu() takes 1 positional argument but 2 were given
This error takes place because you're function is defined to only take one argument. You didn't account for the self argument. To fix this, the code would need to be modified to something like this:
def print_menu(self, newCart):
customer_Cart = newCart
Although as discussed before, you don't need the newCart object to be passed, since you already have access to the newCart object with self. You can then slim down the function to this:
def print_menu(self):
And instead of using customer_Cart to call the functions, you can use self:
while (command != 'a' and command != 'o' and command != 'i' and command != 'r' and command != 'c' and command != 'q'):
command = input('Choose an option: ')
if(command == 'a'):
self.add_item(string)
I would also recommend using elif statements instead of using numerous if statements inside your print_menu() function.

Im trying to use the classes that i made(Vehicle and customer), but i get "TypeError: object() takes no parameters". What am i doing wrong?

Im trying to use the classes that i made(Vehicle and customer), but i get "TypeError: object() takes no parameters" every time i try to create ether of this objects. What am i doing wrong?
import sys
import csv
vehicle = 0
customers = []
class Vehicle:
def _init_(self, number, capacity):
self.number = number
self.capacity = capacity
class customer:
def _init_(self, custNo, xCord, yCord, demand, readyT, dueDate, serviceTime):
self.custNo = custNo
self.xCord = xCord
self.yCord = yCord
self.demand = demand
self.readyT = readyT
self.dueDate = dueDate
self.serviceT = serviceTime
def read():
global vehicle
with open('C101 BUENO.csv') as cvs_file:
cvs_reader = csv.reader(cvs_file, delimiter=';')
line = 0
for row in cvs_reader:
print(line)
if line == 0 or line == 2:
line += 1
elif line == 1:
vehicle = Vehicle(row[0], row[1])
line += 1
else:
c = customer(row[0],row[1],row[2],row[3],row[4],row[5],row[6])
customers.append(c)
line += 1
read()

What is the correct way to format my code?

I have been trying to resolve my script with no results. I can't get
the load data to display. It is saving in members.txt and can read
it manually if opened. If someone can give any other advice on the
script as a whole it would be greatly appreciated.
I have reasearced greatly changed script around still have no luck.
import os if 'file' in vars():
wk_dir = os.path.dirname(os.path.realpath('file')) else:
print('We are running the script interactively')
class playerCLass(object):
name = ""
phone = ""
number = 0
def __init__(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
def setname(self, name):
self.name = name
def setphone(self, phone):
self.phone = phone
def setnumber(self, number):
self.number = number
def getname(self):
return self.name
def getphone(self):
return self.phone
def getnumber(self):
return self.number
def display_data(self):
print("")
print("Member information: ")
print("Name:", self.name)
print("Phone number:", self.phone)
print("Jersey number:", self.number)
def displayMenu():
print("===========Menu Selections===========")
print("1. Display Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Data.")
print("6. Load Data.")
print("9. Exit Program.")
print("")
return int(input("<<Selection>> "))
def printPlayer(players):
print("Current members: ")
if len(players) == 0:
print("No current members in memory.")
else:
x = 1
while x < len(players):
print(x)
x = x + 1
def addPlayer(players):
newName = input("Type in member's name to be added to the roster:")
newPhone = input("Type in the member's phone number:")
newNumber = int(input("Type in the member's jersey number:"))
players[newName] = playerCLass(newName, newPhone, newNumber)
return players
def removePlayer(players):
name = input("Enter member's name to be removed:")
if name in players:
del players[name]
else:
print("member's name not found in list: ")
return players
def editPlayer(players):
oldName = input("Enter the name you want to edit: ")
if oldName in players:
newName = input("Enter a new name: ")
newPhone = input("Enter new phone number: ")
newNumber = int(input("Enter new jersey number: "))
players[oldName] = playerCLass(newName, newPhone, newNumber)
else:
print("No such name in memory: ")
return players
def saveData():
filename = input("Filename to save: ")
print("Saving data...")
outFile = open(filename, "wt")
for x in players.keys():
name = players[int(x)].getname()
phone = players[int(x)].getphone()
number = str(players[x].getnumber())
outFile.write(name + "," + phone + "," + number + "\n")
print("Data saved.")
outFile.close()
def loadData():
players = {}
filename = input("Filename to load: ")
inFile = open(filename, "rt")
print("Loading data...")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, number = inLine.split(",")
players[name] = (name, phone, number)
print("Data Loaded Successfully.")
inFile.close()
return players
print("Welcome to the Team Manager")
players = {}
menuSelection = displayMenu()
print()
while menuSelection != 9:
if menuSelection == 1:
printPlayer(players)
elif menuSelection == 2:
players = addPlayer(players)
elif menuSelection == 3:
players = removePlayer(players)
elif menuSelection == 4:
players = editPlayer(players)
elif menuSelection == 5:
saveData()
elif menuSelection == 6:
loadData()
menuSelection = displayMenu()
print("Exiting Program...")
If your issue is specifically not getting printPlayer to work you can do
def printPlayer(players):
print("Current members: ")
if len(players) == 0:
print("No current members in memory.")
#Iterate through dictionary of player name and player object and call
#display data on each of them
else:
for name, player in players.items():
print(player.display_data())
If you then run the code and input according to the statements you wrote, you should get something like this.
Welcome to the Team Manager
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 1
Current members:
No current members in memory.
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 2
Type in member's name to be added to the roster:Joe
Type in the member's phone number:123
Type in the member's jersey number:456
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 1
Current members:
Member information:
Name: Joe
Phone number: 123
Jersey number: 456
None
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>>

Attempting to place the printed statement into columns

I am having trouble trying to put the output into columns. I have tried using %d but I keep getting TypeError: not all arguments converted during string formatting. what I have so far:
ids = []
scores = []
grades = []
items = []
get input until stopped by 0
id_Test = eval(input("Enter an ID number:"))
while id_Test != 0:
score = eval(input("Enter a score(0.0 - 100.0):"))
ids.append(id_Test)
scores.append(score)
id_Test = eval(input("Enter another ID number:"))
gets the average score
avg_score = sum(scores) / len(scores)
Receives a list of scores and appends the corresponding grade 2 grades list
for score in scores:
if score > avg_score + 10:
grades.append('A')
elif score > avg_score + 5:
grades.append('B')
elif score > avg_score - 5:
grades.append('C')
elif score > avg_score - 10:
grades.append('D')
else:
grades.append('F')
Headers for Columns
print("ID SCORE GRADE")
Columns
for item in range(len(ids)):
print('%%%8d' % (ids[item], scores[item], grades[item]))
I keep getting this TypeError:
Traceback (most recent call last):
File "/Users/Ambriorix/Desktop/$RECYCLE.BIN/LAB3.py", line 40, in <module>
print('%%%8d' % (ids[item], scores[item], grades[item]))
TypeError: not all arguments converted during string formatting

Resources