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.
Related
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)
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 need to somehow access the class dictionary and delete it with the removeClass() function, not sure how to pass the class in it though. This program is supposed to remove the class from the dictionary when the number 2 option is selected.
I'm not sure what to do here.
def prompt():
print('MENU')
print('1 --> Add classes.')
print('2 --> Remove classes.')
print('3 --> View course details.')
print('4 --> View schedule.')
print('5 --> Quit.')
option = int(input('What would you like to choose? '))
while option < 1 or option > 5:
option = int(input('Please enter a valid numerical option: '))
return option
def checkOption(option):
if option == 1:
courseCount = 0
courseCount = courseCounter()
classes = addClasses(courseCount)
elif option == 2:
removeClasses(courses)
elif option == 3:
viewCourseDetails()
elif option == 4:
viewSchedule()
def courseCounter():
courseCount = input('Enter a numerical value of courses only (up to 4): ')
while courseCount.isnumeric() == False:
courseCount = input('Enter a NUMERICAL value of courses only (up to 4): ')
return int(courseCount)
def addClasses(courseCount):
classes = {}
i = 1
while i <= courseCount:
courseName = input('Enter a course name: ')
classes[courseName] = {}
classes[courseName]['Room Number'] = input('Enter a room number: ')
classes[courseName]['Instructor'] = input('Enter a instructor: ')
classes[courseName]['Meeting time'] = input('Enter a meeting time: ')
i = i + 1
return classes
def removeClasses(*****):
courseName = input('Enter the class you would like to remove: ')
if ***** in classes:
del classes[courseName]
print(classes)
def main():
option = prompt()
checkOption(option)
while option > 1 or option < 5:
if option == 5:
break
option = prompt()
checkOption(option)
main()
Through globals() variables so you can pass it across functions:
def prompt():
print('MENU')
print('1 --> Add classes.')
print('2 --> Remove classes.')
print('3 --> View course details.')
print('4 --> View schedule.')
print('5 --> Quit.')
option = int(input('What would you like to choose? '))
while option < 1 or option > 5:
option = int(input('Please enter a valid numerical option: '))
return option
def checkOption(option):
if option == 1:
courseCount = 0
courseCount = courseCounter()
classes = addClasses(courseCount)
elif option == 2 :
if 'classes' in globals() :
removeClasses(globals()['classes'])
else :
print("Insert a class before!")
checkOption(1)
elif option == 3:
viewCourseDetails()
elif option == 4:
viewSchedule()
def courseCounter():
courseCount = input('Enter a numerical value of courses only (up to 4): ')
while courseCount.isnumeric() == False:
courseCount = input('Enter a NUMERICAL value of courses only (up to 4): ')
return int(courseCount)
def addClasses(courseCount):
classes = {}
i = 1
while i <= courseCount:
courseName = input('Enter a course name: ')
classes[courseName] = {}
classes[courseName]['Room Number'] = input('Enter a room number: ')
classes[courseName]['Instructor'] = input('Enter a instructor: ')
classes[courseName]['Meeting time'] = input('Enter a meeting time: ')
i = i + 1
globals()[ 'classes' ] = classes
return classes
def removeClasses(classes):
courseName = input('Enter the class you would like to remove: ')
if courseName in classes:
del classes[courseName]
print(classes)
def main():
option = prompt()
checkOption(option)
while option > 1 or option < 5:
if option == 5:
break
option = prompt()
checkOption(option)
main()
This works on my machine. This also check for existence of classes or redirect user to define classes.
Be awared of globals() behave (e.g. Why are global variables evil?). Otherwise you can define an object (an empty dictionary) and pass it through functions, filling it or check if is empty, that is probably safer.
The simplest way I can think of is as follows. I modified 2 of your functions and made 'classes' global.
classes = {}
def checkOption(option):
global classes
if option == 1:
courseCount = courseCounter()
classes = addClasses(courseCount)
elif option == 2:
removeClasses()
elif option == 3:
viewCourseDetails()
elif option == 4:
viewSchedule()
def removeClasses():
courseName = input('Enter the class you would like to remove: ')
if courseName in classes:
del classes[courseName]
print(classes)
I hope this helps you.
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.
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()