User input not saving into inventory list - python

Basically I am making an app to better assist me at managing my ebay store. I am still very new to programming and OOP. After watching some tutorials I pieced together the following code. Everything so far works pretty well. What I am currently stuck on is when the user inputs an item for inventory, it is not saving it. And, when the user wants to view the inventory the item they added wont populate. Any input or suggestions would be much apprenticed.
def Inventory():
All_Inventory = {}
class Ebay_Inventory:
def __init__(self, manufacturer, object_type, price):
self.manufacturer = manufacturer
self.object_type = object_type
self.price = price
def add_item(self):
manufacturer = input("Enter Manufacturer: ")
object_type = input("Enter what the item is: ")
price = input("Enter price: ")
item_info = Ebay_Inventory(manufacturer, object_type, price)
All_Inventory = item_info
print("Item added successfully")
def delete_item(self):
delete = input("What is the item you want to delete?: ")
if delete in All_Inventory.keys():
del[delete]
print("The item entered has been deleted.")
else:
print("Item not found")
def sale_status(self):
update = input("What is the item you want to update?:")
if update in All_Inventory.keys():
pass
else:
print("Item not found")
user=True
while user:
print("\n1. Add to item inventory")
print("2. Remove item from inventory")
print("3. Update sale status")
print("4. View inventory")
print("5. Exit program")
user_wants=input("What would you like to do today?")
if user_wants=="1":
Ebay_Inventory.add_item(input)
elif user_wants=="2":
Ebay_Inventory.delete_item(input)
elif user_wants=="3":
Ebay_Inventory.sale_status(input)
elif user_wants=="4":
print(All_Inventory)
elif user_wants=="5":
print("\n Thank you for using item inventory.")
break
elif user_wants!="":
print("\n Input not understood. Please try again.")

You need to read about Scope, OOP and dicts:
You are not adding to your Inventory.All_Inventory - you create a new local with All_Inventory = item_info
https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces
Short description of the scoping rules?
You mix up static class attributes and instance attributes, read:
https://docs.python.org/3/tutorial/classes.html#class-objects.
What is the difference between #staticmethod and #classmethod?
You are deleting / accessing your dictionary wrongly - see :
https://docs.python.org/3/tutorial/datastructures.html#dictionaries
Delete an element from a dictionary
Fixed:
class Ebay_Inventory:
Inventory = {} # class property
#staticmethod
def print_inventory():
for k in Ebay_Inventory.Inventory:
for i in Ebay_Inventory.Inventory[k]:
print(k,i)
class Ebay_Item:
def __init__(self, key, manufacturer, object_type, price):
self.manufacturer = manufacturer
self.object_type = object_type
self.price = price
self.key = key
def __str__(self):
return f"{self.manufacturer} {self.object_type} {self.price}"
def __repr__(self):
return str(self)
#staticmethod
def add_item(key=None, man=None, obj=None, pri=None):
# use values if given, else ask - this is for demo purposes only
key = key or input("Enter key: ")
manufacturer = man or input("Enter Manufacturer: ")
object_type = obj or input("Enter what the item is: ")
price = pri or input("Enter price: ")
# create new item
item_info = Ebay_Inventory.Ebay_Item(key, manufacturer, object_type, price)
# add to class member, create key if need be
Ebay_Inventory.Inventory.setdefault(item_info.key,[]).append(item_info)
def delete_item(key=None):
delete = key or input("What is the item you want to delete?: ")
if delete in Ebay_Inventory.Inventory:
del Ebay_Inventory.Inventory[delete]
print("The item entered has been deleted.")
else:
print("Item not found")
def __str__(self):
return Ebay_Inventory.print_inventory()
# add 2 items and print
Ebay_Inventory.add_item(1,"Me","Me",1000)
Ebay_Inventory.add_item(2,"You","You",1000)
Ebay_Inventory.print_inventory()
# remove non existent and existent item and print
Ebay_Inventory.delete_item(3)
Ebay_Inventory.delete_item(2)
Ebay_Inventory.print_inventory()
Output:
1 Me Me 1000
2 You You 1000
Item not found
The item entered has been deleted.
1 Me Me 1000

Sorry to rework your code pretty extensively, but I think this is more like what you are going for:
class EbayInventory:
def __init__(self):
self.all_inventory = []
def print_items(self):
print('Current item list by index:')
for i in range(0, len(self.all_inventory)):
print("{} -> {}".format(i+1, self.all_inventory[i]))
def add_item(self):
manufacturer = input("Enter Manufacturer: ")
object_type = input("Enter what the item is: ")
price = input("Enter price: ")
item = {'manufacturer': manufacturer, 'type': object_type, 'price': price}
self.all_inventory.append(item)
print("Item added successfully")
def delete_item(self):
self.print_items()
delete = int(input("Item id you want to delete: "))
try:
del self.all_inventory[delete - 1]
print("The item entered has been deleted.")
except Exception as e:
print("An error occurred deleting that item, details below")
print(e)
def sale_status(self):
self.print_items()
update_index = int(input("Item id you want to update: "))
if update_index > len(self.all_inventory) or update_index <= 0:
print("You're trying to change an item that doesn't exist!!")
return
print("OK. Let's get that item up to date!")
manufacturer = input("Enter Manufacturer: ")
object_type = input("Enter what the item is: ")
price = input("Enter price: ")
item = {'manufacturer': manufacturer, 'type': object_type, 'price': price}
self.all_inventory[update_index - 1] = item
print("OK. We got that update taken care of")
if __name__ == "__main__":
my_app = EbayInventory()
while True:
print("\n1. Add to item inventory")
print("2. Remove item from inventory")
print("3. Update sale status")
print("4. View inventory")
print("5. Exit program")
user_wants = input("Please enter the number corresponding to how you would like help: ")
if user_wants == "1":
my_app.add_item()
elif user_wants == "2":
my_app.delete_item()
elif user_wants == "3":
my_app.sale_status()
elif user_wants == "4":
my_app.print_items()
elif user_wants == "5":
print("Thank you for using item inventory.")
break
else:
print("Input not understood. Please try again.")
You had a variable user that did nothing. You can simply enter an infinite loop with while True:. If you wanted to loop the way you did, then instead of a break you could have put a user = False to break out of the loop. This is sometimes a nifty trick, but doesn't make sense here I think. It seemed to me the inventory was really the only thing that would benefit by being stored in your class, and the methods could then access it to adjust it via a self.all_inventory. I moved your code to ask for item inputs to the add_item() and sale_status() methods, so now the main block of code looks a lot cleaner. I also wrapped it in if __name__ == "__main__": so that you can import this class to another project without running the entire program! I threw in some basic error checking with try: and except: clauses also. I think you were misunderstanding the difference between a Class and an Instance. So in my code the Class is EbayInventory, but the Instance is my_app. You create instances of your class just like I did with my_app = EbayInventory() and then the self now refers to my_app. In this manner I can call my_app.add_item(). You can have several instances of objects though, and they each have their own space in your computers memory. So you could have said:
app1 = EbayInventory()
app2 = EbayInventory()
app1.add_item()
And only the app1 will have any items, whereas app2 is still an empty list, but still has the methods to build an inventory via app2.add_item(). To answer your main question though, you never call your function Inventory() and therefore it doesn't exist to hold your information. When you call item_info = Ebay_Inventory(manufacturer, object_type, price) in fact you are making an Instance of a class, which is really nonsensical to do here because that means on the next line you could say item_info.add_item() and this would make another instance, yet you are not saving this information anywhere so you can never retrieve it!

Related

Creating new instances of a class from user input

I am trying to make a weekly meal prep program in Python. Part of that program is having a database of recipes that the user has entered. I thought the best way to make this would be to make a class Recipe where it stores the title, ingredients (as a dictionary with the key being the ingredient and the amount being value) and then the instructions. However I can't find a way to make a new variable each time I try to input a new recipe.
This is my class code
class Recipe:
def __init__(self):
ingredients = {}
while True:
ingredient = input('Type in an ingredient. Type finish when you have added in all the ingredients. ')
if ingredient == 'finish':
break
amount = input("How much of this ingredient? ")
ingredients[ingredient]=amount
self.ingredients = ingredients
self.title = input('What is the name of the recipe? ')
self.instructions = input('Type out your recipe instructions; ')
meal1 = Recipe()
print(meal1.title)
print(meal1.ingredients)
print(meal1.instructions)
Basically this works for creating one recipe. But instead of the ''' meal1 = Recipe()''' I want to create a new recipe each time the user selects the option in the main menu to 'add a recipe' how can I accomplish this without making lots of pre-named variables.
I think the better approach is to separate between user input (menu) and the recipe class
class Recipe:
def __init__(self):
ingredients = {}
while True:
ingredient = input('Type in an ingredient. Type finish when you have added in all the ingredients. ')
if ingredient == 'finish':
break
amount = input("How much of this ingredient? ")
ingredients[ingredient]=amount
self.ingredients = ingredients
self.title = input('What is the name of the recipe? ')
self.instructions = input('Type out your recipe instructions; ')
class Menu:
def __init__(self):
self.recipes = []
while True:
print("=" * 20)
print('1. Add a recipe')
print('2. Print the recipes')
print('3. Quit')
print("=" * 20)
choice = input('What would you like to do? ')
if choice == '1':
self.add_recipe()
elif choice == '2':
self.print_recipes()
elif choice == '3':
break
else:
print('That is not a valid choice. Please try again.')
def print_recipes(self):
for recipe in self.recipes:
print(recipe.title)
print(recipe.ingredients)
print(recipe.instructions)
def add_recipe(self):
recipe = Recipe()
self.recipes.append(recipe)
Menu()
The recipe is saved in variable self.recipes. With this way, you can save as many recipes as you want.
if I understand your question properly, you want to create a fresh, brand new object every time that a user creates a recipe after inserting the instruction Type out your recipe instructions, then you can delete your object using __del__ function in your class.
class Recipe:
def __init__(self):
ingredients = {}
while True:
ingredient = input('Type in an ingredient. Type finish when you have added in all the ingredients. ')
if ingredient == 'finish':
break
amount = input("How much of this ingredient? ")
ingredients[ingredient]=amount
self.ingredients = ingredients
self.title = input('What is the name of the recipe? ')
self.instructions = input('Type out your recipe instructions; ')
def __del__(self):
print("I have been destroyed.")
and to create a new object every time:
for i in range(5):
meal1 = Recipe()
print(meal1.title)
print(meal1.ingredients)
print(meal1.instructions)
del meal1
#print(meal1) # runs into NameError: name 'meal1' is not defined
note that how __del__ behaves, it may not be called every time if the reference to the object is not counted to zero. you may see this and this.

Saving an Object and being able to update its attributes

I am creating a POS system in Python, which is almost complete. (GUI not included). However, I want to be able to store the items that a user registers.
I tried saving the object to a file, but that did not help:
with open('myObject.pkl', 'wb') as outp:
itemObject = Item("", 0, 0)
pickle.dump(itemObject, outp, pickle.HIGHEST_PROTOCOL)
Even after I input the item's details ("name",price,stock) an exit the program, when I started it again I had to register the item all over again.
I also searched online on the matter, but all the results I got did not support updating the attributes of the object in the file.
I've also checked more examples on the forum, but none of them suit my needs well, like this one: Saving an Object (Data persistence), Python- Saving list of objects and its attributes
If it helps, here is where I defined the class and object:
class Item:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
itemObject = Item("", 0, 0)
Here is the function that updates the class attributes based on user input:
def regItem():
name = input("What is your item called? ")
name.lower()
if name == 'exit':
exit()
try:
price = int(input("How much does it cost? "))
name.lower()
if name == 'exit':
exit()
if (isinstance(price, int)):
stock = input("How much stock is available for this item? ")
name.lower()
if name == 'exit':
exit()
itemObject.name = name
itemObject.price = price
itemObject.stock = stock
int(itemObject.price)
int(itemObject.stock)
print("Item",itemObject.name,"priced at",itemObject.price,"with available stock of",itemObject.stock,"has been registered")
start()
except ValueError:
print("Must be a number")
regItem()
I'm learning Python as my first language, and I'm also new to stack overflow. Any help would be appreciated. Thanks in advance.
You need to conditionally load the object you are trying to persist.
import os
import pickle
class Item:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def __str__(self):
return f"Item {self.name} priced at {self.price} with available stock of {self.stock}"
def regItem():
name = input("What is your item called? ")
name.lower()
if name == 'exit':
exit()
try:
price = int(input("How much does it cost? "))
name.lower()
if name == 'exit':
exit()
if (isinstance(price, int)):
stock = input("How much stock is available for this item? ")
name.lower()
if name == 'exit':
exit()
itemObject = Item(name, price, stock)
print(f"{itemObject} has been registered")
return itemObject
except ValueError:
print("Must be a number")
return regItem()
def start(obj):
print("Starting {}".format(obj))
def main():
filename = 'myObject.pkl'
if os.path.exists(filename):
with open(filename, 'rb') as inp:
itemObject = pickle.load(inp)
else:
itemObject = regItem()
with open('myObject.pkl', 'wb') as outp:
pickle.dump(itemObject, outp, pickle.HIGHEST_PROTOCOL)
start(itemObject)
main()
Run this once to enter in the data. Run it again and it will start with the same object you started with.

How can I define an object in this cart method without overwriting the previous one?

I am coding a Shopping Website in Python, and am having trouble with the 4th option in the code, the checkout, since if a user tries to checkout without entering any data in, it will give an error, and I'm not sure how to fix this, since if I just make a cart, it will overwrite the data. Here is the code -
#Created by Aykhan Salimov on 09.22.2020
#This is a class for books
class Book:
def __init__(self, number, title, author, genre, price):
self.number = number
self.title = title
self.author = author
self.genre = genre
self.price = price
def __str__(self):
return "This book's name is " + self.title + "\n" + "This book's author is " + self.author + "\n" + "This book's genre is " + self.genre + "\n" + "This book's price is " + self.price
#This is a class for the inventory of books for sale
class Inventory:
def __init__(self, make):
self.make = make
def books(self):
print("Current Books")
f.open = open("booklist.txt", "r")
f.read()
f.close()
def add_book(self):
print("Please specify the book information for the book you wish to add")
addbookn = input("Please input the number of the book you wish to add: ")
addbookt = input("Please input the title of the book you wish to add: ")
addbooka = input("Please input the author of the book you wish to add: ")
addbookg = input("Please input the genre of the book you wish to add: ")
addbookp = input("Please input the price of the book you wish to add: ")
newBook = Book(addbookn, addbookt, addbooka, addbookg, addbookp)
f.open = open("booklist.txt", "r")
f.write("/n%s" % newBook)
def display(self):
print("===========================================")
print("Item number:", book0.number)
print("Title:", book0.title)
print("Author:", book0.author)
print("Genre:", book0.genre)
print("Price:", book0.price)
print("===========================================")
print("Item number:", book1.number)
print("Title:", book1.title)
print("Author:", book1.author)
print("Genre:", book1.genre)
print("Price:", book1.price)
print("===========================================")
print("Item number:", book2.number)
print("Title:", book2.title)
print("Author:", book2.author)
print("Genre:", book2.genre)
print("Price:", book2.price)
print("===========================================")
print("Item number:", book3.number)
print("Title:", book3.title)
print("Author:", book3.author)
print("Genre:", book3.genre)
print("Price:", book3.price)
print("===========================================")
print("Item number:", book4.number)
print("Title:", book4.title)
print("Author:", book4.author)
print("Genre:", book4.genre)
print("Price:", book4.price)
print("===========================================")
#This is a class for the user's cart
class Cart(Inventory):
def add_book(self):
numberbook = int(input("What is the number of the book you would like to buy?"))
self.cartlist = []
if numberbook == 1000:
self.cartlist.append(23.99)
if numberbook == 1001:
self.cartlist.append(3.99)
if numberbook == 1002:
self.cartlist.append(3.99)
if numberbook == 1003:
self.cartlist.append(9.99)
if numberbook == 1004:
self.cartlist.append(61.99)
if numberbook <= 999 or numberbook >= 1005:
print("You made a wrong selection")
return self.cartlist
def checkout(self):
total = sum(self.cartlist)
print("Thank you for shopping! Your total is:", total)
return self.cartlist
return self.cartlistfh
book0 = Book("1000", "Science: A Visual Encyclopedia", "Chris Woodford", "Science", "$23.99")
book1 = Book("1001", "My First Human Body Book", "Patricia J. Wyennevand Donald M Silver", "Science", "$3.99")
book2 = Book("1002", "The Runaway Children", "Sandy Taylor", "Fiction", "$9.99")
book3 = Book("1003", "The Tuscan Child", "Rhys Bowen", "Fiction", "$9.99")
book4 = Book("1004", "Science: A Visual Encyclopedia", "Chris Woodford", "Science", "$23.99")
loop = True
while(loop):
print("1: Display Books")
print("2: Add to Cart")
print("3: Show Cart")
print("4: Checkout")
print("5: Quit")
userinput = str(input("Select an Option: "))
if userinput == '1':
myInventory = Inventory("Inventory")
myInventory.display()
print("These are the book for sale")
print("You will now be returned to the home screen")
continue
if userinput == '2':
loop2 = True
while(loop2):
myCart = Cart("Cart")
myCart.add_book()
print("Book(s) added successfully!")
userin2 = str(input("Would you like to continue buying books? Type 1 if yes and 2 if no!"))
if userin2 == '1':
print("OK! Let's continue")
continue
if userin2 == '2':
print("OK. You will now be returned to the home screen")
loop2 = False
continue
if userinput == '3':
#Work in progress
print(".")
continue
if userinput == '4':
#Issues with this method, since creating a new object doesn't have the previous one's information, and this code gives an error if the cart is blank
myCart.checkout()
loop = False
if userinput == '5':
print("Thank you for shopping!")
loop = False
Right now, you have a couple of problems. The first is that every time you call Cart's add_book function, you overwriting the list of books. The easiest way to fix this is to move cartlist to Cart's __init__ method. You can do this without losing the functionality of Inventory's __init__ with a call to super, like so:
def __init__(self, make):
super().__init__(make)
self.cartlist = []
If you are not familiar, super() is a way to reference the parent class of an object, in this case Inventory.
The second issue with your code is that you are creating a new cart every time someone selects option 2. This, again, wipes cartlist, since a new cart will have an empty cartlist. I would recommend moving the instantiation of myCart (and myInventory, for that matter) up above the while loop where you define all of your books. That way, these objects will only be created once, and you won't run into issues trying to check out before the cart is created.

Updating a list in a Python class

I want to update a list to include new items added by a user. There are a few conditions such as the code must be 7 digits long. If the code already exists, the system will notify the user. If the user tries to add another copy of 'up' with a different code, the system will not allow it. It will make them try again as the code must be the same. Eventually I will include a video number, so if there are two copies of 'up' they will have two different video numbers but the same video code.
Can someone show me why the following code is not working for me?
all_movies = []
class Movie(object):
movie_list = []
def __init__(self, code, title, director):
self.code = code
self.title = title
self.director = director
Movie.movie_list.append(self)
#staticmethod
def add_movie():
mv_code = input("Code of movie: ")
movie_code = int(mv_code)
movie_title = input("Name of movie: ")
movie_director = input("Director: ")
if len(mv_code) == 7:
all_movies.append(Movie(movie_code, movie_title, movie_director))
print("movie added to database")
else:
print("the code must be 7 digits long, add movie again.")
def check_validity(movie_code, all_movies):
if movie_code in all_movies:
return True
else:
return False
if check_validity(movie_code, all_movies):
all_movies[all_movies] += Movie
print()
print("updated")
else:
all_movies[movie_code] = [movie_code, movie_title, movie_director]
def main():
movie1 = Movie(1122334, 'Up', 'Director')
movie2 = Movie(1231235, 'Taxi Driver', 'Film-maker')
This is the error message that I am receiving:
all_movies[movie_code] = [movie_code, movie_title, movie_director]
IndexError: list assignment index out of range
First of all this structure is not suitable for your desires.
About the error you got, I should say that you have to define you all movies as a dictionary not a list (because of the that you want to use for each movie).
try this:
all_movies = {}
in you add_movie method:
#staticmethod
def add_movie():
mv_code = input("Code of movie: ")
movie_code = int(mv_code)
movie_title = input("Name of movie: ")
movie_director = input("Director: ")
if len(mv_code) == 7:
if movie_code in all_movies.keys():
print("the movie already exists")
# what do you want to happen here ?
else:
all_movies[movie_code] = (movie_code, movie_title, movie_director)
print("movie added to database")
else:
print("the code must be 7 digits long, add movie again.")
This will add a movie to the all_movies and you don't need the rest your code, and i didn't understand the usage of init and movie_list.
Try this, then tell me what happens if the code already exists in the movies, I will update my answer for you.
UPDATE:
According to your desires in comment the method will updated to something like this:
#staticmethod
def add_movie():
mv_code = input("Code of movie: ")
movie_code = int(mv_code)
movie_title = input("Name of movie: ")
movie_director = input("Director: ")
if len(mv_code) == 7:
if movie_code in all_movies.keys():
print("the movie is already exists, adding it with another video number")
# all_movies[movie_code][-1] is the last video with an existing key
# all_movies[movie_code][-1][-1] last video number generated
new_video_number = all_movies[movie_code][-1][-1] + 1
all_movies[movie_code].append([movie_title, movie_director, new_video_number]) # adding it with new video number
print("movie added to database with new video number")
else:
all_movies[movie_code] = []
all_movies[movie_code].append([movie_title, movie_director, 1]) # 1 is the first movie added(video number)
print("movie added to database")
else:
print("the code must be 7 digits long, add movie again.")
This will returns all_movies like this:
{
'1231235':[
['Taxi Driver', 'Film-maker', 1]
]
'1122334':[
['Up', 'Director',1],
['Up', 'Director',2],
['Up', 'Director',3],
]
'1122333':[
['Another movie', 'Another Director',1],
['Another movie', 'Another Director',2],
]
}
The last element of inner list are the video_numbers that generated automatically by system.

Tying values to keys in a dictionary and then printing

This is a smaller portion of the main code I have been writing. Depending on user selection they can add player informationa and then print the information from the dictionary player roster. I want to store the information and then print in this format but I havent been able to figure out how to do this.
Name ****
Phone Number ****
Jersey Number ****
Im new to dictionaries but I have spent hours reading and searching over the past couple of days about dictionaries and have tried several different ways to do this but failed. I have gotten the closest the way I have it setup now but it still doesnt work right. I feel like I am storing the information incorrectly into the dictionary for starters, any help would be greatly appreciated.
player_roster = {}
def display_roster(self): #Print Roster
if len(player_roster) != 0:
for x in player_roster.keys():
print('Name:', x, 'Phone Number:', player_roster[x])
else: #Print No One on Roster
len(player_roster) == []
print('No names have been entered:')
def add_player(self,): #Enter Members Name
name = input('Enter New Players Name:')
phone_number = input('Enter Players Phone Number:')
jersey_number = int(input('Enter Players Jersey Number'))
player_roster[name] = phone_number, 'Jersey Number', jersey_number
#If I input Toby as Name 444-444 as Phone Number and 3 as Jersey number it outputs like this
Name: Toby Phone Number: ('444-4444', 'Jersey Number', 3)
# I would like it to output like
Name: Toby
Phone Number: 444-4444
Jersey Number: 3
There are some things i would change in your code but to keep this close to what you asked for take a look at this:
def display_roster():
if len(player_roster) != 0:
for x in player_roster.keys():
print('Name:', x)
print('Phone Number:', player_roster[x][0])
print('Jersey Number:', player_roster[x][1])
else:
print('Roster is empty.')
return
player_roster = {}
def add_player():
name = input('Enter New Players Name:\t')
phone_number = input('Enter Players Phone Number:\t')
jersey_number = int(input('Enter Players Jersey Number:\t'))
player_roster[name] = [phone_number, jersey_number]
return
add_player()
display_roster()
# PRINTS:
#Name: Toby
#Phone Number: 444-4444
#Jersey Number: 3
Printing in multiple lines gives you the result you want. As stated in the comments this can also be done with a single print() statement but i do not think compact code makes much difference to you yet.
Further, this len(self.player_roster) == [] line does not make sense. This is as good as simply writing True in a line. The "emptiness" of the team is checked by the else:.
Finally, i would slightly change the way players are stored in the "Roster" dictionary and have it like this: {"Toby": ['444-4444', 3], ...}
I would propose that you replace the print statement to this:
print(" Name: %s \n Phone Number: %s \n Jersey Number: %d") % player_roster[x]
You're pretty much there. The below modification would allow you to print as you need (and is slightly more readable):
class PlayerDictionary():
def __init__(self):
pass
player_roster = {}
def display_roster(self): #Print Roster
if len(self.player_roster) != 0:
for key, value in self.player_roster.iteritems():
print(str(key) + ": " + str(value))
else: #Print No One on Roster
len(self.player_roster) == []
print('No names have been entered:')
def add_player(self,):
self.player_roster['Name'] = input('Enter New Players Name:')
self.player_roster['Phone Number'] = input('Enter Players Phone Number:')
self.player_roster['Jersey Number'] = int(input('Enter Players Jersey Number'))
if __name__ == "__main__":
player = PlayerDictionary()
player.add_player()
player.display_roster()
A slightly more maintainable solution would be to create a class for Player. Set the properties on the object and overload the str function e.g.
class Player(object):
def __init__(self):
self.__name = ""
self.__phone_number = ""
self.__jersey_number = ""
#property
def name(self):
return self.__name
#property
def phone_number(self):
return self.__phone_number
#property
def jersey_number(self):
return self.__jersey_number
#name.setter
def name(self, val):
self.__name = val
#phone_number.setter
def phone_number(self, val):
self.__phone_number = val
#jersey_number.setter
def jersey_number(self, val):
self.__jersey_number = val
def __str__(self):
return ("Name: %s\nPhone Number: %s\nJersey Number: %s" % (str(self.__name), str(self.__phone_number), str(self.__jersey_number)))
if __name__ == "__main__":
player = Player()
player.name = input('Enter New Players Name:')
player.phone_number = input('Enter Players Phone Number:')
player.jersey_number = int(input('Enter Players Jersey Number'))
print(player)

Categories