I have to create a team roster that saves and loads the data. I have it to the point where everything else works but saving and loading.
memberList = []
#get first menu selection from user and store in control value variable
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 displayData(self):
print("")
print("Player's Information")
print("-------------------")
print("Player's Name:", getName)
print("Player's Telephone number:", getPhone)
print("Player's Jersey number:", getNumber)
def displayMenu():
print("==========Main Menu==========")
print("1. Display Team Roster")
print("2. Add Member")
print("3. Remove Member")
print("4. Edit Member")
print("9. Exit Program")
print()
return int(input("Selection>"))
menuSelection = displayMenu()
def printMembers(memberList):
print("Current members: ")
if len(memberList) == 0:
print("No current members in memory.")
else:
x = 1
while x < len(memberList):
print(memberList[x],)
x = x + 1
def addPlayer(memberList): # players as an argument
newName = input("Add a player's Name: ")
newPhone = input("Telephone number: ")
newNumber = input("Jersey number: ")
memberList.append(newName)
return memberList
def removePlayer(memberList):
removeName = input("What name would you like to remove? ", )
# Don't redefine it!
if removeName in memberList:
del memberList[removeName]
else:
print("Sorry", removeName, "was not found!")
return memberList
def editPlayer(memberList):
oldName = input("What name would you like to change? ", )
if oldName in memberList:
newName = input("What is the new name? ")
print("***", oldName, "has been changed to", newName)
else:
print("***Sorry", oldName, "was not found!")
return memberList
def saveData(memberList):
filename=input("Filename to save: ", )
print("saving data...")
outfile=open(filename, "wt")
filename= '/Users\nativ\ Documents'
for x in memberList:
name = memberList[x].getName()
phone = memberList[x].getPhone()
number = memberList[x].getNumber()
outfile.write("name","age", 'number')
print("Data Saved")
outfile.close()
def loadData():
filename = input("Filename to load: ")
inFile = open(filename, "rt")
def exitProgram(memberList):
print("Exiting Program...")
while menuSelection != 9:
if menuSelection == 1:
printMembers = printMembers(memberList)
menuSelection = displayMenu()
elif menuSelection == 2:
memberList = addPlayer(memberList)
menuSelection = displayMenu()
elif menuSelection == 3:
memberList = removePlayer(memberList)
menuSelection = displayMenu()
elif menuSelection == 4:
memberList = editPlayer(memberList)
menuSelection = displayMenu()
elif menuSelection == 5:
memberList = saveData(memberList)
menuSelection = displayMenu()
elif menuSelection == 6:
memberList = loadData()
menuSelection = displayMenu()
print('Welcome to the Team Manager')
displayMenu()
This is the error code that I am getting
Traceback (most recent call last):
File "C:/Users/nativ/PycharmProjects/Week2/Week 5.py", line 98, in <module>
memberList = saveData(memberList)
File "C:/Users/nativ/PycharmProjects/Week2/Week 5.py", line 73, in saveData
name = memberList[x].getName()
TypeError: list indices must be integers or slices, not str
Try name = memberList[int(x)].getName(). When it reads the data from a file it reads a string, and in order to put that into a list you need to make it an integer.
Related
import re
#list of user information
list_id = []
list_name = []
list_surname = []
list_age = []
list_nationalid = []
list_mail = []
class Record:
def __init__(self,programName):
self.programName = programName
self.loop = True
print("welcome {}.".format(programName))
def program(self):
while True: #the loop gonna keep ask if input is not a correct number
try:
userInput = int(input ("what you want to do?\n1-addRecord\n2-removeRecord\n3-listRecord\n4-exitRecord\n"))
if userInput < 5 and userInput > 0:
self.menu(userInput)
break
else:
print("pls enter a valid number")
except Exception :
print("pls enter a valid number again ")
def menu(self,userInput):
self.userInput = userInput
if userInput == 1:
print("addRecord is opening")
self.addRecord()
if userInput == 2:
print("removeRecord is opening")
self.removeRecord()
if userInput == 3:
print("list Record are opening")
self.listRecord()
if userInput == 4:
self.exitRecord()
def addRecord(self):
while True:
user_name = input("pls enter your name")
if user_name == re.findall("[^a-z]"):
list_name.append(user_name)
print ("addRecord_name worked")
break
else:
print ("enter a valid name")
while True:
user_surname = input("pls enter your name")
if user_surname == re.findall("[^a-zA-E]"):
list_surname.append(user_surname)
print ("addRecord_surname worked")
break
else:
print ("enter a valid surname")
while True:
user_age = input("pls enter your age")
if user_age == re.findall("[^0-9]"):
list_age.append(user_age)
print ("addRecord_age worked")
break
else:
print ("enter a valid age")
while True:
user_nationalid = input("pls enter your national id")
if user_name == re.findall("[^0-9]"):
list_nationalid.append(user_nationalid)
print ("addRecord_nationalid worked")
break
else:
print ("enter a valid national id")
while True:
user_mail = input("pls enter your name")
if user_name == re.search("#" and ".com" , user_mail):
list_mail.append(user_mail)
print ("addRecord_mail worked")
break
else:
print ("enter a valid national id")
def removeRecord(self):
pass
def listRecord(self):
pass
def backToMenu(self):
pass
def exitRecord(self):
pass
System = Record("admin")
System.program() #its for keep working `program`
I trying to make a program which is add/remove/list data. the while loop which is in program is not breaking. even If I enter my name at addRecord function it prints "pls enter a valid number again ". problem is not about addRecord function because I already have that problem before I write these function. any advice or explain ?
Here is the corrected code, however your implementation of the menu is still not the best practices.
import re
list_id = []
list_name = []
list_surname = []
list_age = []
list_nationalid = []
list_mail = []
class Record:
def __init__(self,programName):
self.programName = programName
self.loop = True
print("welcome {}.".format(programName))
def program(self):
while True: #the loop gonna keep ask if input is not a correct number
try:
userInput = int(input ("what you want to do?\n1-addRecord\n2-removeRecord\n3-listRecord\n4-exitRecord\n"))
if userInput < 5 and userInput > 0:
self.menu(userInput)
else:
print("pls enter a valid number")
except Exception :
print("pls enter a valid number again ")
def menu(self,userInput):
self.userInput = userInput
if userInput == 1:
print("addRecord is opening")
self.addRecord()
if userInput == 2:
print("removeRecord is opening")
self.removeRecord()
if userInput == 3:
print("list Record are opening")
self.listRecord()
if userInput == 4:
self.exitRecord()
def addRecord(self):
while True:
user_name = input("pls enter your name")
if re.findall("[^a-z]", user_name) == []:
list_name.append(user_name)
print ("addRecord_name worked")
break
else:
print("enter a valid name")
while True:
user_surname = input("pls enter your surname")
if re.findall("[^a-zA-E]", user_surname) == []:
list_surname.append(user_surname)
print ("addRecord_surname worked")
break
else:
print("enter a valid surname")
while True:
user_age = input("pls enter your age")
if re.findall("[^0-9]", user_age) == []:
list_age.append(user_age)
print ("addRecord_age worked")
break
else:
print("enter a valid age")
while True:
user_nationalid = input("pls enter your national id")
if re.findall("[^0-9]", user_nationalid) == []:
list_nationalid.append(user_nationalid)
print ("addRecord_nationalid worked")
break
else:
print("enter a valid national id")
while True:
user_mail = input("pls enter your email")
if re.search("#" and ".com" , user_mail):
list_mail.append(user_mail)
print ("addRecord_mail worked")
break
else:
print ("enter a valid email")
def removeRecord(self):
pass
def listRecord(self):
pass
def backToMenu(self):
pass
def exitRecord(self):
pass
System = Record("admin")
System.program() #its for keep working `program`
I have a inventory program that works. I am trying to save out the data (item names and qty) which are held in a list called inventory. So they can be reused for the next time the program is launched and edited at a later date.
My inventory program code:
import os
class Inventory:
def __init__(self):
self.item = []
self.qty = []
def remove(self, name):
ix = self.item.index(name)
self.item.pop(ix)
self.qty.pop(ix)
def add(self, name, qty):
self.item.append(name)
self.qty.append(qty)
def update(self, name, update):
if update >= 0:
self.qty[self.item.index(name)] += update
elif update <= -1:
self.qty[self.item.index(name)] += update
def search(self, name):
pos = self.item.index(name) if name in self.item else -1
if pos >= 0:
return self.item[pos], self.qty[pos]
else:
return None
def __str__(self):
out = ""
zipo = list(zip(self.item, self.qty))
for foobar in zipo:
out += f"Item : {foobar[0]} \nQuantity : {foobar[1]}\n"
out += "----------\n"
return out
def menuDisplay():
"""Display the menu"""
print('=============================')
print('= Inventory Management Menu =')
print('=============================')
print('(1) Add New Item to Inventory')
print('(2) Remove Item from Inventory')
print('(3) Update Inventory')
print('(4) Search Item in Inventory')
print('(5) Print Inventory Report')
print('(99) Quit')
def add_one_item(inventory):
print('Adding Inventory')
print('================')
while True:
try:
new_name = input('Enter the name of the item: ')
assert new_name.isalpha(), "Only letters are allowed!"
new_qty = int(input("Enter the quantity of the item: "))
inventory.add(new_name, new_qty)
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def remove_one_item(inventory):
print('Removing Inventory')
print('==================')
removing = input('Enter the item name to remove from inventory: ')
inventory.remove(removing)
def ask_exit_or_continue():
return int(input('Enter 98 to continue or 99 to exit: '))
def update_inventory(inventory):
print('Updating Inventory')
print('==================')
item = input('Enter the item to update: ')
update = int(input(
"Enter the updated quantity. Enter 5 for additional or -5 for less: "))
inventory.update(item, update)
def search_inventory(inventory):
print('Searching Inventory')
print('===================')
search = input('Enter the name of the item: ')
result = inventory.search(search)
if result is None:
print("Item not in inventory")
else:
name, qty = result
print('Item: ', name)
print('Quantity: ', qty)
print('----------')
def print_inventory(inventory):
print('Current Inventory')
print('=================')
print(inventory)
def main():
inventory = Inventory()
while True:
try:
menuDisplay()
CHOICE = int(input("Enter choice: "))
if CHOICE in [1, 2, 3, 4, 5]:
if CHOICE == 1:
add_one_item(inventory)
elif CHOICE == 2:
remove_one_item(inventory)
elif CHOICE == 3:
update_inventory(inventory)
elif CHOICE == 4:
search_inventory(inventory)
elif CHOICE == 5:
print_inventory(inventory)
exit_choice = ask_exit_or_continue()
if exit_choice == 99:
exit()
elif CHOICE == 99:
exit()
except Exception as e:
print("Invalid choice! try again!"+str(e))
print()
# If the user pick an invalid choice,
# the program will come to here and
# then loop back.
main()
The program is called Cleancopy.py and I am trying to save the data to a TextEdit file or excel document called Inventory.
The code that is suppose to export the name and qty in the list called inventory.
How do I fix this? This is my first time trying to save this data. Thank you for your time.
The quickest way to save and retrieve lists is to save them to a text file, then use eval to read the lists. For the inventory, update the data file each time an item is added or removed. Load the data when the inventory object if first instantiated.
Try this update:
class Inventory:
def __init__(self):
.....
self.load()
def remove(self, name):
....
self.save()
def add(self, name, qty):
.....
self.save()
def update(self, name, update):
.....
self.save()
.....
def save(self):
with open('inventory.dat','w') as f:
f.write(str(self.item) + '\n' + str(self.qty))
def load(self):
from os import path
if path.exists('inventory.dat'):
with open('inventory.dat','r') as f:
lns = f.readlines()
self.item = eval(lns[0])
self.qty = eval(lns[1])
For more data, you should use a csv file.
it is showing an error when i enter "aa"(without quotes in lend_book function in book name ).
class library:
def __init__(self,list,library_name):
self.listofbook = list
self.library_name = library_name
self.lendbook = {}
self.Ldict = {}
def display_book(self):
for book in self.listofbook:
if book not in self.Ldict:
print(book)
def lend_book(self):
name_book1 = input('Enter the book you lend\n>')
name_ur1 = input('Enter your name\n>')
bdict = {name_book1:name_ur1}
if name_book1 in self.listofbook:
self.Ldict.update(bdict)
self.listofbook.remove(name_book1)
print("book has been issue to you")
else:
print(f"{name_book1} was not available\n{self.Ldict[name_book1]} currently owns the book")
def donate_book(self):
print("Enter the name or list of book that you wants to donate\n>")
donate_book = input()
self.listofbook.extend(donate_book)
def return_book(self):
name_book2 = input('Enter the book you want to return\n>')
name_ur2 = input('Enter your name\n>')
bdict2 = {name_book2:name_ur2}
del self.Ldict[name_book2]
self.listofbook.extend(name_book2)
def addBook(self):
book = input()
self.listofbook.append(book)
print("Book has been added to the book list")
def printLend(self):
if self.Ldict=={}:
print("No book is lended")
else:
print('those who lend books')
for key in self.Ldict:
print(f'Book {key} and Name {self.Ldict[key]}')
def Option(self,a):
if a==1:
return self.display_book()
elif a==2:
return self.lend_book()
elif a==3:
return self.donate_book()
elif a==4:
return self.return_book()
elif a==5:
return self.printLend()
elif a==6:
return self.addBook()
else:
print("Enter a vaild option")
if __name__=='__main__':
sumit = library(["jungalbook","thatbook","a","b","c","d"],"sumit_library")
while True:
print(f"Welcome to the {sumit.library_name}")
print("Enter options to continue")
print("1-display book")
print("2-lend book")
print("3-donate book")
print("4-return book")
print("5-details for books were lended")
print("6-Add book")
op = int(input())
sumit.Option(op)
print("Press 'q' to quit and 'c' to continue")
user_choice2 = ''
while(user_choice2!="c" and user_choice2!="q"):
user_choice2 = input()
if user_choice2 == "q":
exit()
elif user_choice2 == "c":
continue
please help
I'm trying to call the "name" under 'create():' in 'show():', but it says it's not defined. How can I save my input in 'create():', so I can use it in the other subroutines (in 'show():' for this example).
Thank you
I have tried to ask the user input after the choice part, but it doesn't solve it. I keep getting the same error.
import sys
class data:
name = ""
average = ""
def menu():
print("1) Data input")
print("2) Print data")
print("3) Give file name")
print("4) Save")
print("5) Read file")
print("0) Stop")
choice = int(input("Give your choice: "))
print()
return choice
def save(datalist, namea):
f = open(namea, "w")
for data in datalist:
row = str("{};{}").format(data.name, data.average)
f.write(row)
f.write("\n")
f.close()
def read(datalist, namea):
f = open(namea, "r")
for row in f:
row = row.split(";")
dataa = data()
dataa.name = str(row[0])
dataa.average = float(row[1])
datalist.append(dataa)
return datalist
def printt(datalist):
for data in datalist:
print(data.name, data.average)
def name():
namea = str(input("Give a name: "))
return namea
def inputt(datalist):
dataa = data()
dataa.name = str(input("Give a name: "))
dataa.average = float(input("Give the average (float): "))
datalist.append(dataa)
print()
return(datalist)
def main():
try:
datalist = []
while True:
choice = menu()
if (choice == 1):
datalist = inputt(datalist)
elif (choice == 2):
printt(datalist)
elif (choice == 3):
namea = name()
elif (choice == 4):
save(datalist, namea)
elif (choice == 5):
datalist = read(datalist, namea)
elif (choice == 0):
print("The program was closed {} at {}".format(datetime.datetime.now().strftime('%d.%m.%Y'), datetime.datetime.now().strftime('%H:%M:%S')))
return False
except Exception:
sys.exit(0)
main()
I excpect it to print the name I input in 1), when I call 2).
For example:
choice 1)
1) Give name: Daniel
choice 2)
2) Prints: Hello Daniel
you got a problem with your Scope.
The name variable is only local.
See https://www.programiz.com/python-programming/global-local-nonlocal-variables for more Information.
a hotfix would be using global-variables instead, or as Aaron D. Rodriguez suggested passing the name as parameter to the show-function.
def lista():
print("1) Write name.")
print("2) Print written name.")
print("0) Stop.")
choice = int(input("Give your choice: "))
return choice
def create():
global name
name = input("Give name: ")
return(name)
def show():
global name
print(name)
return
def main():
print("Choose from the following list:")
while True:
choice = lista()
if (choice == 0):
print("Thanks for using the program!")
break
elif (choice == 1):
create()
elif (choice == 2):
show()
else:
print("Input not detected.\nStopping.")
break
main()
You would have to have show() include a parameter in it. For example:
def show(n):
print(n)
So that when you call show(n), it prints whatever you include as n.
So if you called show(name). It would print out name.
def show(n):
print(n)
show(name) #This would print out name.
You also don't need return unless you are returning a value. Return doesn't make the code go back, it just makes the function return a value. So you do need return for list() and create(), but not for show(n).
Edit
You also would want to set the user input as a variable when you call create.
def main():
print("Choose from the following list:")
while True:
choice = lista()
if (choice == 0):
print("Thanks for using the program!")
break
elif (choice == 1):
name = create() #Here is where you should change it
elif (choice == 2):
show(name)
else:
print("Input not detected.\nStopping.")
break
I am new to python and doing some programming for school I have written code for a roster system and I am supposed to use dictionaries. I keep getting error No module named 'players_Class'
Can someone tell me what I am doing wrong
class Players:
def __init__(self, name, number, jersey):
self.__name = name
self.__number = number
self.__jersey = jersey
def setname(self, name):
self.__name = name
def setnumber(self, number):
self.__number = number
def setjersey(self, jersey):
self.__jersey = jersey
def getname(self):
return self.__name
def getnumber(self):
return self.__number
def getjersey(self):
return self.__jersey
def displayData(self):
print("")
print("Player Information ")
print("------------------------")
print("Name:", self.__name)
print("Phone Number:", self.__number)
print("Jersey Number:", self.__jersey)
import players_Class
def displayMenu():
print("1. Display Players")
print("2. Add Player")
print("3. Remove Player")
print("4. Edit Player")
print("9. Exit Program")
print("")
return int(input("Selection> "))
def printPlayers(players):
if len(players) == 0:
print("Player not in List.")
else:
for x in players.keys():
players[x].displayData(self)
def addplayers(players):
newName = input("Enter new Players Name: ")
newNumber = int(input("Players Phone Number: "))
newJersey = input("Players Jersey Number: ")
players[newName] = (newName, newNumber, newJersey)
return players
def removeplayers(players):
removeName = input("Enter Player Name to be removed: ")
if removeName in players:
del players[removeName]
else:
print("Player not found in list.")
return players
def editplayers(players):
oldName = input("Enter the Name of the Player you want to edit: ")
if oldName in players:
newName = input("Enter the player new name: ")
newNumber = int(input("Players New Number: "))
newJersey = input("Players New Jersey Number: ")
players[oldName] = petClass.Pet(newName, newNumber, newJersey)
else:
print("Player Not Found")
return players
print("Welcome to the Team Manager")
players = {}
menuSelection = displayMenu()
while menuSelection != 9:
if menuSelection == 1:
printPlayers(players)
elif menuSelection == 2:
players = addplayers(players)
elif menuSelection == 3:
players = removeplayers(players)
elif menuSelection == 4:
players = editplayers(players)
menuSelection = displayMenu()
print ("Exiting Program...")
you have unused
import players_Class
statement in your code. just erase it!