python class import issue - python

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!

Related

How to use if statements in classes

I'm trying to make a simple library where the user can add and remove books from his shopping cart, but I don't know how to use if statements with OOP and classes.
try:
class library:
def __init__(self, books, customer):
self.books = books
self.customer = customer
# sign:
check = input("manager account(1), customer account(2): ")
if check == "2":
#age >= 18
age = int(input("enter your age: "))
if age >= 18:
#name
name = input("enter your firstname: ")
# ID
import random
x = "ID"+str(random.randint(101,999))
print(f"your ID is: {x}")
print("you should memorize it")
y = input("enter password that has at list 8 caracterse: ")
# Password
while len(y) < 8:
y = input("enter password that has at list 8 caracterse: ")
print(f"your password is: {y}")
print("you should memorize it")
data = [x,y]
choice_1 = input("check your shopping cart(1): \nadd books to your shopping cart(2): \nremove books from your shopping cart(3): ")
if choice_1 == "1":
def __str__(self):
return f"customer {self.customer} bought those books{self.books}"
elif choice_1 == "2":
def __iadd__(self, other):
self.books.append(other)
return self
order = library(["the golsen company"],"Mr.asad")
print(order.books)
order += input("enter a book: ")
print(order.books)
except ValueError as ages:
print(ages)
I don't know if this is the right way to use the if statement with classes so if you can just give me an example to show how it's done correctly?
OK, I have rewritten your code to implement it in a more organized way. Your class "library" was not really a library at all; it is a class for "orders", and I have renamed it as such. I didn't know what you wanted for the manager account, so the manager account just assigns a fake user name without requiring a signup. I also fixed the spelling errors and the tabbing.
import random
import sys
class Order:
def __init__(self, books, customer):
self.books = books
self.customer = customer
def __iadd__(self, other):
self.books.append(other)
return self
def __isub__(self, other):
self.books.remove(other)
return self
def __str__(self):
return f"custumer {self.customer} bought those books {self.books}"
# sign in.
check = input("manager account(1),custumer account(2): ")
if check == '1':
x = 'manager'
if check == "2":
#age >= 18
age = int(input("enter your age: "))
if age < 18:
print("Sorry, you must be at least 18.")
sys.exit(0)
#name
name = input("enter your firstname: ")
# ID
x = "ID"+str(random.randint(101,999))
print(f"your ID is: {x}")
print("you should memorize it")
# Password
y = input("enter password that has at least 8 characters: ")
while len(y) < 8:
y = input("enter password that has at least 8 characters: ")
print(f"your password is: {y}")
print("you should memorize it")
# Main menu.
order = Order( [], x )
while True:
print('---')
choice_1 = input("1. check your shopping cart\n2. add books to your shopping cart\n3. remove books from your shopping cart\n4. quit: ")
if choice_1 == "1":
print( order )
elif choice_1 == "2":
order += input("enter a book: ")
elif choice_1 == "3":
book = input("enter a book: ")
if book in order.books:
order -= book
else:
print( f"{book} is not in your cart." )
elif choice_1 == "4":
break
when you said "fonction", I think you mean "function". When you make a try: block, you must also add an except: block. Also, don't put code directly in the class. Put it inside a function (a.k.a methods). I put the code starting from # sign in the __int__ method. We generally don't put methods (functions) inside other methods. So, put the __str__ and __iadd__ methods outside the __init__ method. To call it, use self.__str__() and self.__iadd__().
Here is the updated code:
try:
class library:
def __init__(self, books, customer):
self.books = books
self.customer = customer
# sign:
check = input("manager account(1), customer account(2): ")
if check == "2":
# age >= 18
age = int(input("enter your age: "))
if age >= 18:
# name
name = input("enter your firstname: ")
# ID
import random
x = "ID" + str(random.randint(101, 999))
print(f"your ID is: {x}")
print("you should memorize it")
y = input("enter password that has at list 8 caracterse: ")
# Password
while len(y) < 8:
y = input("enter password that has at list 8 caracterse: ")
print(f"your password is: {y}")
print("you should memorize it")
data = [x, y]
choice_1 = input("check your shopping cart(1): \nadd books to your shopping cart(2): ")
if choice_1 == "1":
self.__str__()
elif choice_1 == "2":
self.__iadd__()
# age < 18
elif age < 18:
print("this library is not for your age")
def __iadd__(self, other):
self.books.append(other)
return self
def __str__(self):
return f"customer {self.customer} bought those books{self.books}"
except:
pass
order = library(["the golsen company"], "Mr.asad")
print(order.books)
order += input("enter a book: ")
print(order.books)

key error problem ,when enter "aa" in lendfuction (in book name)

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

this program never makes it past the menu choices it continuously ask for a menu option??

I'm not sure why it keeps asking to enter a menu choice after I enter one!
When I run it consistently asks me to enter a number, but it doesn't run the functions associated with the numbers
not sure if you needed the class butI included it anyway
import pickle
class Contact:
def __init__(self, name, phone, email):
self.__name = name
self.__phone = phone
self.__email = email
def set_name(self, name):
self.__name = name
def set_phone(self, phone):
self.__phone = phone
def set_email(self, email):
self.__email = email
def get_name(self):
return self.__name
def get_phone(self):
return self.__phone
def get_email(self):
return self.__email
these are the menu options that I have, no matter what number i enter it asks me to enter another number
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5
FILENAME = 'contacts.txt'
def main():
mycontacts = load_contacts()
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == LOOK_UP:
look_up(mycontacts)
elif choice == ADD:
add(mycontacts)
elif choice == CHANGE:
change(mycontacts)
elif choice == DELETE:
delete(mycontacts)
save_contacts(mycontacts)
def load_contacts():
try:
input_file = open(FILENAME, 'rb')
contact_dct = pickle.load(input_file)
input_file.close()
except:
contact_dct = {}
return contact_dct
def get_menu_choice():
print()
print('Menu')
print('-------------------')
print('1. Look up an contact')
print('2. Add a new contact')
print('3. Change an existing contact')
print('4. Delet a contsct')
print('5. Quit the program')
print()
choice = int(input('Enter your choice: '))
while choice < LOOK_UP or choice > QUIT:
choice = int(input('Enter a vaild choice: '))
return choice
def look_up(mycontacts):
name = input('Enter a name: ')
print(mycontacts.get(name, 'That name is not found'))
def add(mycontacts):
name = input('Name: ')
phone = input('Phone: ')
email = input('Email: ')
entry = contact.Contact(name, phone, email)
if name not in mycontacts:
mycontacts[name] = entry
print('The entry has been added.')
else:
print('That name already exists.')
def change(mycontacts):
name = input('Enter a name: ')
if name in mycontacts:
phone = input('Enter the new phone number: ')
email = input('New Email: ')
entry = contact.Contact(name, phone, email)
mycontacts[name] = entry
print('information updated')
else:
print('not found')
def delete(mycontacts):
name = input('Enter a name: ')
if name in mycontacts:
del mycontacts[name]
print('Entry deleted')
else:
print('That name not found')
def save_contacts(mycontacts):
output_file = open(FILENAME, 'wb')
pickle.dump(mycontacts, output_file)
output_file.close()
main()
I believe the problem is in the following function:
def get_menu_choice():
print()
print('Menu')
print('-------------------')
print('1. Look up an contact')
print('2. Add a new contact')
print('3. Change an existing contact')
print('4. Delet a contsct')
print('5. Quit the program')
print()
choice = int(input('Enter your choice: '))
while choice < LOOK_UP or choice > QUIT:
choice = int(input('Enter a vaild choice: '))
return choice
First issue: If the first choice entered is within bounds, it is never returned from get_menu_choice().
Second issue: If the first choice entered is not within bounds, your while loop just returns the immediate next choice.
How to fix it: Move the return statement outside the while loop in get_menu_choice(). Also, move choice = get_menu_choice() to the bottom of the while loop in main(), and set choice's initial value to get_menu_choice().
Hope this helps.
P.S. What happens if the choice entered by the user is not an integer? What happens if the user enters a character, string, or control character? I would consider additional error-handling for erroneous input.

Rock paper scissors menu error

Here is code I have so far whenever the menu appears and I press 1 for start a new game it says wrong choice try again.
import random
import pickle
class GameStatus():
def __init__(self, name):
self.tie = 0
self.playerWon = 0
self.pcWon = 0
self.name = name
def get_round(self):
return self.tie + self.playerWon + self.pcWon + 1
# Displays program information, starts main play loop
def main():
print("Welcome to a game of Rock, Paper, Scissors!")
print("What would you like to choose?")
print("")
game_status = welcomemenu()
while True:
play(game_status)
endGameSelect(game_status)
def welcomemenu():
while True:
print("[1]: Start New Game")
print("[2]: Load Game")
print("[3]: Quit")
print("")
menuselect = input("Enter your choice: ")
if menuselect in [1, 2, 3]:
break
else:
print("Wrong choice. select again.")
if menuselect == 1:
name = input("What is your name?: ")
print("Hello %s.") % name
print("Let's play!")
game_status = GameStatus(name)
elif menuselect == 2:
while True:
name = input("What is your name?: ")
try:
player_file = open('%s.rsp' % name, 'r')
except IOError:
print("Sorry there is no game found with name %s") % name
continue
break
print("Welcome back %s.") % name
print("Let's play!")
game_status = pickle.load(player_file)
displayScoreBoard(game_status)
player_file.close()
elif menuselect == 3:
print("Bye!!!")
exit()
return
return game_status
def play(game_status):
playerChoice = int(playerMenu())
pcChoice = pcGenerate()
outcome = evaluateGame(playerChoice, pcChoice)
updateScoreBoard(outcome, game_status)
def playerMenu():
print("Select a choice: \n [1]: Rock \n [2]: Paper \n [3]: Scissors\n")
menuSelect = input("What will it be? ")
while not validateInput(menuSelect):
invalidChoice(menuSelect)
menuSelect = input("Enter a correct value: ")
return menuSelect
def validateInput(menuSelection):
if menuSelection in [1, 2, 3]:
return True
else:
return False
def pcGenerate():
pcChoice = random.randint(1,3)
return pcChoice
# Calculate ties,wins,lose
def evaluateGame(playerChoice, pcChoice):
rsp = ['rock', 'paper', 'scissors']
win_statement = ['Rock breaks scissors', 'Paper covers rock', 'Scissors cut paper']
win_status = (playerChoice - pcChoice) % 3
print("You have chosen %s") % rsp[playerChoice - 1]
what_to_say =("Computer has chose %s") % rsp[pcChoice - 1]
if win_status == 0:
what_to_say +=(" as Well. TIE!")
elif win_status == 1:
what_to_say +=(". %s. You WIN!") % win_statement[playerChoice - 1]
else:
what_to_say +=(". %s. You LOSE!") % win_statement[pcChoice - 1]
print("what_to_say")
return win_status
# Update track of ties, player wins, and computer wins
def updateScoreBoard(outcome, game_status):
if outcome == 0:
game_status.tie += 1
elif outcome == 1:
game_status.playerWon += 1
else:
game_status.pcWon += 1
# If user input is invalid, let them know.
def invalidChoice(menuSelect):
print(menuSelect,("is not a valid option. Please select 1-3"))
# Print the scores before terminating the program.
def displayScoreBoard(game_status):
print("")
print("Statistics:")
print(("Ties: %d") % game_status.tie)
print(("Player Wins: %d") % game_status.playerWon)
print(("Computer Wins: %d") % game_status.pcWon)
if game_status.pcWon > 0:
print("Win/Loss Ratio: %f") % (float(game_status.playerWon) / game_status.pcWon)
else:
print("Win/Loss Ratio: Always Win.")
print("Rounds: %d") % game_status.get_round()
def endGameSelect(game_status):
print("")
print("[1]: Play again")
print("[2]: Show Statistics")
print("[3]: Save Game")
print("[4]: Quit")
print("")
while True:
menuselect = input("Enter your choice: ")
if menuselect in [1, 2, 3, 4]:
break
else:
print("Wrong input.")
if menuselect == 2:
displayScoreBoard(game_status)
endGameSelect(game_status)
elif menuselect == 3:
f = open("%s.rsp" % game_status.name, 'w')
pickle.dump(game_status, f)
f.close()
print("Your game is saved successfully.")
endGameSelect(game_status)
elif menuselect == 4:
print("Bye!!!")
exit()
main()
When you use input(), you get a string rather than an int.
You should change:
menuselect = input("Enter your choice: ")
to this:
menuselect = int(input("Enter your choice: "))
To get it as an integer, that way it will work with the rest of your script.

Save and Load data in Python 3

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.

Categories