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

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

Related

I can't break the while loop

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`

'Not defined' when using subroutine

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

python class import issue

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!

Python Invalid Syntax under Def mainmenu

I am getting this invalid syntax for if selection == 1: under def mainmenu(): Do not understand why I am getting this error. Please help me figure this out. I completely doesnt make any sense to me why its there.
contacts = {}
class person:
def ___init__(self,first,last,number):
self.first = first
self.last = last
self.number = number
def get_info(self):
print(first,last,number)
class friend(person):
def __init__(self,email,bday):
self.email = email
self.bday = bday
def get_info_friend(self):
super().get_info()
print(email,bday)
def add_a_contact():
choice = int(input("Contact type: \n\t 2: Person \nEnter an option here:"))
first = input("Enter the first name:")
last = input("Enter the last name:")
number = input("Enther the number:")
if choice == 1:
email = input("Email Address is:")
bday = input("Their bday is:")
return Friend(email,bday,first,last,number)
return person(first,last,number)
def add_contact_to_dict():
contact = add_a_contact()
contacts[contact.last_name] = contact
def lookup():
last = input("What is their last name?:")
if last in contacts:
contact = contacts[last]
print("Name&number: ", contact.first,contact.last,contact.number)
if type(friend) is friend:
print("Email and Bday is: ", contact.email,contact.bday)
def mainmenu():
selection = 0
temp = ""
while selection != 3:
print("Select an option: \n\t 1: Add \n\t 2: Lookup \n\t 3: Exit")
selection = int(input("Enter an option:")
if selection == 1:
temp = add_contact_to_dict()
elif selection == 2:
lookup()
elif selection == 3:
pass
else:
print("Not a valid option")
if __name__ == "__mainmenu__":
mainmenu()
So when you are asked for the input under selection, you need another bracket to for the "int" part. Hopefully, that should solve your issue.

Invalid syntax error on the elif statement

I'm writing this program that lets users choose an option to display, change,add, remove, write or quit
I keep getting invalid syntax error on this elif statement in my program and i dont know why?
DISPLAY = 'D'
CHANGE = 'C'
ADD = 'A'
REMOVE = 'R'
WRITE = 'W'
QUIT = 'Q'
#main function
def main ():
print()
print()
print('\t Wombat Valley Tennis Club')
print('\t Member Register')
print('\t =======================')
main_dic = {}
with open ('wvtc_data.txt','r')as x:
for line in x:
line = line.rstrip ('\n')
items = line.split (':')
key,value = items[0], items[1:]
main_dic[key] = values
choice = input('choice: ')
while choice != QUIT:
choice = get_menu_choice()
if choice==DISPLAY:
display(main_dic)
elif choice==CHANGE:
change(main_dic)
elif choice== REMOVE:
remove (main_dic)
elif choice==WRITE:
write(main_dic)
def get_menu_choice():
print()
print("\t\t Main Menu")
print()
print('\t<D>isplay member details')
print('\t<C>hange member details')
print('\t<A>dd a new member')
print('\t<R>emove a member')
print('\t<W>rite updated details to file')
print('\t<Q>uit')
print()
print('Your choice (D, C, A, R, W OR Q)?\t[Note: Only Uppercase]')
print()
choice = input("Enter your choice: ")
while choice < DISPLAY and choice < CHANGE or choice > QUIT:
choice = input ('Enter your choice: ')
return choice
def display(main_dic):
name = input('Type the name of the member:')
print()
print (main_dic.get(name, 'not found!'))
print()
print()
def change(main_dic):
name=input("Enter the member number")
print()
print(main_dic.get(name,'not found!'))
print()
NAME = 1
EMAIL = 2
PHONE = 3
print('Please select')
print('==============')
print('Change Name<1>')
print('Change E-mail<2>')
print('Change Phone Number<3>')
print()
if choose == NAME:
new_name = input('Enter the name: ')
print()
print("Data has been changed")
main_dic[name][0]=new_name
print (mem_info[name])
print()
elif choose == EMAIL:
new_email=input('Enter the new email address:')
print ('Email address has been changed')
#change the data
main_dic[name][1]=new_email
print(mem_info[name])
print()
elif choose == PHONE:
new_phone = int (input('Enter the new phone number'))
print ("phone number has been changed")
main_dic[name][2]=new_phone
print(main_dic[name])
print
def write(main_dic):
print()
name = input ("Enter the name of a member:")
print()
print (mem_info.get(name,'Not found!'))
print()
main()
main()
Also any help or suggestions in making this code work are appreciated.
It's a formatting problem. The elifs have to start in the same column as the if to which they belong.
Example
if something:
do_somtething()
elif something_else:
do_the_other_thing()

Categories