Jason Ray Jason Ray - 1 year ago 74
Python Question

adding accessing and deleting items from a python list

Learning lists and arrays and I am not sure where I went wrong with this program. Keep in mind I am still new to python. Unsure if i am doing it right. Ive read a few tutorials and maybe Im not grasping list and arrays. Ive got it to where you can type a name but it doesnt transfer to a list and then i get list is empty constantly as well as other errors under other functions in the code.

def display_menu():
print("1. Roster ")
print("2. Add")
print("3. Remove ")
print("4. Edit ")
print("9. Exit ")
return int(input("Selection> "))

def printmembers():
if namelist > 0:
print("List is empty")

def append(name):

def addmember():
name = input("Type in a name to add: ")

def remove():

def removemember():
m = input("Enter Member name to delete:")
if m in namelist:
print(m, "was not found")

def index():

def editmember():
old_name = input("What would you like to change?")
if old_name in namelist:
item_number = namelist.index(old_name)
new_name = input("What is the new name? ")
namelist[item_number] = new_name
print(old_name, 'was not found')

print("Welcome to the Team Manager")

namelist = 0

menu_item = display_menu()

while menu_item != 9:
if menu_item == 1:
elif menu_item == 2:
elif menu_item == 3:
elif menu_item == 4:
menu_item = display_menu()
print("Exiting Program...")

Answer Source

For starting out, you've got the right ideas and you're making good progress. The main problem is how you defined namelist = 0, making it a number. Instead, namelist needs to be an actual list for you to add or append anything to it. Also, you're append() method is not necessary since once you define namelist as a list, you can use the built-in list.append() method, without having to write your own method. So here are a few suggestions/corrections, which once you have the basis working correctly, you should be able to work out the rest of the bug fixes and logic.

  1. Since you don't have any main() method, you can define namelist on the first line of code, before any other code, so that it is referenced in each method:
    namelist = [] # an empty list

  2. Change addmember() method to:

    def addmember(): name = raw_input("Type in a name to add: ") namelist.append(name)

  3. Since namelist is a list, we can use the built-in len() method on nameslist to check if it's empty when printing out its contents (if any):

    def printmembers(): if len(namelist) > 0: # Get the length of the list print(namelist) else: print("List is empty")

Now that the Add() menu option is working for adding a name to the namelist, you should be able to implement removing, and editing names to the list using similar logic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download