Updating a list in a Python class - python

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.

Related

Any idea why this code doesn't work as intended?

This is my first python code. The code is supposed to prompt user with options and then perform actions based on the user input.
However, when I run the code, instead of prompting for the menu I get the prompt to enter the movie title. Here's the code I have written so far.
# code starts here
MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find your movie or 'q' to quit: "
movies = []
def add_movie():
title = input("Enter the movie title: ")
director = input("Enter the movie director: ")
year = input("Enter the movie year: ")
movies.append({
'title': title,
'director': director,
'year': year
})
def show_movies():
for movie in movies:
print_movie(movie)
def print_movie(movie):
print(f"Title : {movie['title']}")
print(f"Director : {movie['director']}")
print(f"Release Year : {movie['year']}")
def find_movie():
search_title = input("Enter movie title you are looking for: ")
for movie in movies:
if movie["title"] == search_title:
print_movie(movie)
user_options = {
"a" : add_movie(),
"l" : show_movies(),
"f" : find_movie()
}
def menu():
selection = input(MENU_PROMPT)
while selection != "q":
if selection in user_options:
selected_function = user_options[selection]
selected_function()
else:
print('Unknown command, Please try again')
selection = input(MENU_PROMPT)
menu()
#code ends here
When you create a dictionary with a value being a function, it will run that function to fill in the value of the dictionary. So that is why it is running add_movie() first before anything else.
The proper way to do your menu would be like this:
>>> def x():
... print("hi")
...
>>> y = {'a':x}
>>> y['a']()
hi
We save the value of the dictionary as the function name, then call it by adding the () to the returned value.

Both if statements and the else printing out, however, none of it is getting the url database

This program is a console application that displays an Application Title and the Menu Options for the user, displays a list of recipe categories (i.e. Beef, Chicken, Vegan, Side, Desert, etc.), displays a list of meals based on a user selected category, and displays meal information (Directions) based on a user selected meal. I only need help with displaying the list of meals for the user selected category.
I am using a website that provides free JSON API's for this program that all work fine. The program shows the categories and recipes but wont show the individual meals for each of the category.
Its weird because I put print() statements after the if statements in the function where it gets the meals by category to try to debug it but, it prints both the pint(1) and print(2) statements so it does the getting stuff right but still also prints the else statement. This section of code is part of the recipes.py file (found under) in the search_meal_by_categories function.
This is what I put in to debug it to figure out why it prints out both the if and else:
def search_meal_by_category(categories):
lookup_category = input("Enter a category: ")
found = False
for i in range(len(categories)):
category = categories[i]
if category.get_category().lower() == lookup_category.lower():
found = True
print(1)
if found:
meals = requests.get_meals_by_category(lookup_category)
list_meals_by_category(lookup_category, meals)
print(2)
else:
print("Invalid Category, please try again")
Its very weird because it shows the recipe if you type it is but not the meals in that category. In the command menu you can:
("1 - List all Categories")
("2 - List all Meals for a Category")
("3 - Search Meal by Name")
("0 - Exit the program")
Thus far, I can put in the command 1 and 3 but not 2 or 0. There are 3 different python files for this and I included each of the 3 with only that specific meals by category function from each file to make it easier (I hope?).
Basically, the goal is to ask the program to show each meal in the category you type in. Thus far, it only shows the categories and a recipes instructions if you type in the name of the recipe. However, I dint include that since its working fine.
(object.py file)
class Category:
def __init__(self, category):
self.__category = category
def get_category(self):
return self.__category
def set_category(self, category):
self.__category = category
class Meal:
def __init__(self, meal_id, meal, meal_thumb):
self.__meal_id = meal_id
self.__meal = meal
self.__meal_thumb = meal_thumb
def get_meal_id(self):
return self.__meal_id
def set_meal_id(self, meal_id):
self.__meal_id = meal_id
def get_meal(self):
return self.__meal
def set_meal(self, meal):
self.__meal = meal
def get_meal_thumb(self):
return self.__meal_thumb
def set_meal_thumb(self, meal_thumb):
self.__meal_thumb = meal_thumb
(requests.py file)
from urllib import request, parse
import json
from objects import Category, Meal
def get_categories():
url = 'https://www.themealdb.com/api/json/v1/1/list.php?c=list'
f = request.urlopen(url)
categories = []
try:
data = json.loads(f.read().decode('utf-8'))
for category_data in data['meals']:
category = Category(category_data['strCategory'])
categories.append(category)
except (ValueError, KeyError, TypeError):
print("JSON format error")
return categories
def get_meals_by_category(category):
url = 'https://www.themealdb.com/api/json/v1/1/filter.php?c=Seafood' + category
f = request.urlopen(url)
meals = []
try:
data = json.loads(f.read().decode('utf-8'))
for meal_data in data['meals']:
category = Meal(meal_data['idMeal'],
meal_data['strMeal'],
meal_data['strMealThumb'])
meals.append(category)
except (ValueError, KeyError, TypeError):
print("JSON Format error")
return meals
This is the last file of the 3 and I think where the problem lies. I put a print(1), print(2) statement after each if and it printed out both those AND the else statement? Basically, all it shows right now is "Invalid Category, please try again" like 10 times.
import requests
def show_title():
print("My recipes Program")
print()
def show_menu():
print("COMMAND MENU")
print("1 - List all Categories")
print("2 - List all Meals for a Category")
print("3 - Search Meal by Name")
print("0 - Exit the program")
print()
def list_categories(categories):
print("CATEGORIES")
for i in range(len(categories)):
category = categories[i]
print(category.get_category())
print()
def list_meals_by_category(category, meals):
print(category.upper() + " MEALS ")
for i in range(len(meals)):
meal = meals[i]
print(meal.get_meal())
print()
def search_meal_by_category(categories):
lookup_category = input("Enter a category: ")
found = False
for i in range(len(categories)):
category = categories[i]
if category.get_category().lower() == lookup_category.lower():
found = True
break
if found:
meals = requests.get_meals_by_category(lookup_category)
list_meals_by_category(lookup_category, meals)
else:
print("Invalid Category, please try again")
Please comment if you need any more information, this is my first time doing a python project this big (I know this may seem very easy to everyone because everyone on here is a genius). I have genuinely been staring at this for 2 days now. Thanks everyone for any help!
Did you mean to write this:
def search_meal_by_category(categories):
lookup_category = input("Enter a category: ")
found = False
for i in range(len(categories)):
category = categories[i]
if category.get_category().lower() == lookup_category.lower():
found = True
break
if found:
meals = requests.get_meals_by_category(lookup_category)
list_meals_by_category(lookup_category, meals)
else:
print("Invalid Category, please try again")
I have unindented the if found: part, so that when you get the found = True; break then it skips the rest of the for and detects found.

Generating Random Combinations of Dictionary Key and Value Sets

I am creating a program to sort through a music library file. I have this one particular function, generateRandomPlaylist(musicLibDictionary), that I am stuck on.
The function needs to randomly pick a key from the dictionary and randomly assign one of the values to the key. For instance the artists in the dictionary include The Who, Adele and The Beatles. The respective albums include Tommy; 19, 21, 25; Abbey Road, Let It Be. I need the program to randomly pick one of the keys (the artists) and then randomly pick one of the key's values. The randomly generated playlist needs to have all three artists, not repeats, but different albums from the artist. The way I have it set up, the output doesn't necessarily use all three artists. Sample output should look like:
Here is your random playlist:
- 25 by Adele
- Abbey Road by The Beatles
- Tommy by The Who
Each time the function is called, the playlist should be different. Like I said, right now the function doesn't run properly, and I also get a printing error saying I cannot concatenate a list and a string, so I don't know where I am going wrong.
The code for the program is below:
# importing pickle
import pickle
import random
# declaration of functions
def displayMenu():
print("Welcome to Your Music Library")
print("Options:")
print("\t1) Display Library")
print("\t2) Display all artists")
print("\t3) Add an album")
print("\t4) Delete an album")
print("\t5) Delete an artist")
print("\t6) Search Library")
print("\t7) Generate a random playlist")
print("\t8) Make your own playlist")
print("\t9) Exit")
def displayLibrary(musicLibDictionary):
for key in musicLibDictionary:
print("Artist: " + key)
print("Albums: ")
for album in musicLibDictionary[key]:
print("\t- " + album)
def displayArtists(musicLibDictionary):
print("Displaying all artists:")
for key in musicLibDictionary:
print(" - " + key)
def addAlbum(musicLibDictionary):
artistName = input("Please enter the name of the artist you would like to add: ")
albumName = input("Please enter the name of the album you would like to add: ")
if artistName in musicLibDictionary.keys():
musicLibDictionary[artistName].append(albumName)
else:
musicLibDictionary[artistName] = [albumName]
def deleteAlbum(musicLibDictionary):
artist = input("Enter artist: ")
albumToBeDeleted = input("Enter album: ")
if artist in musicLibDictionary.keys():
if albumToBeDeleted in musicLibDictionary[artist]:
musicLibDictionary[artist].remove(albumToBeDeleted)
return True
else:
return False
else:
return False
def deleteArtist(musicLibDct):
artistToBeDeleted = input("Enter artist to delete: ")
if artistToBeDeleted in musicLibDct.keys():
del musicLibDct[artistToBeDeleted]
return True
else:
return False
def searchLibrary(musicLibDictionary):
searchTerm = input("Please enter a search term: ")
searchTerm = searchTerm.lower()
print("Artists containing" + searchTerm)
for key in musicLibDictionary.keys():
if searchTerm.lower() in key.lower():
print("\t - ", end="")
print(key)
print("Albums containing" + searchTerm)
for album in musicLibDictionary[key]:
print("\t- " + album)
for key in musicLibDictionary.keys():
for album in musicLibDictionary[key]:
if searchTerm in album.lower():
print("\t - ", end="")
print(album)
def generateRandomPlaylist(musicLibDictionary):
print("Here is your random playlist:")
for artist in musicLibDictionary.keys():
artistSelection = random.choice(list(musicLibDictionary.keys()))
albumSelection = random.choice(list(musicLibDictionary.values()))
print("\t-" + albumSelection + "by" + artistSelection)
def loadLibrary(libraryFileName):
fileIn = open(libraryFileName, "rb")
val = pickle.load(fileIn)
val = dict(val)
return val
def saveLibrary(libraryFileName, musicLibDictionary):
fileIn = open(libraryFileName, "wb")
pickle.dump(musicLibDictionary, fileIn)
def main():
musicLib = loadLibrary("musicLibrary.dat")
userChoice = ""
while (userChoice != 7):
displayMenu()
userChoice = int(input("> "))
if userChoice == 1:
displayLibrary(musicLib)
elif userChoice == 2:
displayArtists(musicLib)
elif userChoice == 3:
addAlbum(musicLib)
elif userChoice == 4:
deleteAlbum(musicLib)
elif userChoice == 5:
deleteArtist(musicLib)
elif userChoice == 6:
searchLibrary(musicLib)
elif userChoice == 7:
generateRandomPlaylist(musicLib)
elif userChoice == 8:
saveLibrary("musicLibrary.dat", musicLib)
# Call main
main()
Here's one way to do it, if I understand correctly that you want each artist exactly once in a random order and a random album from each artist:
def generateRandomPlaylist(musicLibDictionary):
print("Here is your random playlist:")
artists = list(musicLibDictionary.keys())
random.shuffle(artists) # Perform an in-place shuffle
for artistSelection in artists:
albumSelection = random.choice(list(musicLibDictionary[artistSelection]))
print("\t-" + albumSelection + "by" + artistSelection)
We know we want all the artists exactly once, but in a random order. Since the keys of the dictionary are the artists, then we can just perform a random.shuffle on the keys to get a random ordering of the artists. Then we have to look into each artist's albums (musicLibDictionary[artist]) and make a random.choice to pick out one album at random.
What your code is doing, on a line by line basis, is the following:
def generateRandomPlaylist(musicLibDictionary):
print("Here is your random playlist:")
for artist in musicLibDictionary.keys(): # For each artist
artistSelection = random.choice(list(musicLibDictionary.keys())) # Choose one artist randomly (not necessarily the one in your for loop)
albumSelection = random.choice(list(musicLibDictionary.values())) # Choose a random album list (musicLibDictionary.values() returns a list of lists, so you're just choosing a random discography (list) from a random artist)
print("\t-" + albumSelection + "by" + artistSelection) # Because this is not indented into your loop, you're likely only getting the last one chosen
The reason you were getting issues appending a string and a list (not allowed in python directly, you must cast the list to a string first) is that your albumSelection variable was a full list of the albums from a random artist, not necessarily even the artist in the artistSelection variable. Your musicLibDictionary.values() was returning something like [['Tommy'], ['19', '21', '25'], ['Abbey Road', 'Let It Be']]. random.choice picks a random value out of the list provided to it so given a list like [[1,2,3], [4,5,6]] it could pick out [1,2,3].

User input not saving into inventory list

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!

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