Creating a menu using a dictionary - python

I need help with the below code please, I am trying to create a piece of code that displays true or false at the beginning with a given course code using a function. four letters, 3 digits, and a 'space' in between them if that condition is true then the program will ask the user to choose the menu with 6 options using a dictionary. please explain to me where did I go wrong.
Thank you
What I have tried:
def CourseCode(input_word):
COURSES = ['SCIN', 'ENGG', 'MATC', 'BCSE', 'BCMS', 'ENGS', 'MGMT', 'COMM']
VALID_DIGITS = (1, 2, 3, 4, 6)
if user_code == 'SCIN 123':
return True
else:
return False
def user_menu():
add_course = {}
add_course['1'] ="Add new Course:"
add_course[True] = "Course added"
add_course[False]= "Invalid course code: The format is XXXX 111"
list_course = {}
list_course['2'] = "List Course:"
print("SCIN 123", "ENGG 101", "MATC 354", "MATC 355", "BCSE 202", "CCMS 100", "ENGS 202" )
stu_enrol = {}
stu_enrol['3'] = "Enrol Student"
stu_enrol = input("Please enter student family name: ")
stu_enrol[new_student]=[]
print(stu_enrol)
stu_enrol = input(f"Please enter student first initial {new_student}: ")
stu_enrol = input(f"Please enter course to enrol or X to finish {new_student}: ")
if key_data in stu_enrol:
print("Successfully enrolled.")
elif(key_data != add_course ):
print("Sorry you need to enrol in at least two courses")
elif(key_data != stu_enrol):
print("Sorry, already enrolled in that course")
elif(key_data != CourseCode):
print("Sorry, that course does not exist.")
else:
print("Sorry, a maximum of four courses are allowed")
lis_enr_stu = {}
lis_enr_stu['4']={"List Enrolments for a Student"}
lis_all_enr = {}
lis_all_enr['5']={"List all Enrolments"}
user_exit['6'] = "Quit"
if action() is False:
break
input_word = input("Please select menu choice: ")
CourseCode = CourseCode(input_word)

Related

Delete a line (name, contactnumber, emailaddress) by just searching for name in a phonebook

Good evening, I have a phonebook code but I am missing the delete feature. I cannot seem to make the delete feature work. All other features like insert, view, add contacts are working already.
I created a phnoebook txt file to store any entries.
phonebook = "d://phonebook.txt"
pbfile = open(phonebook, "a+")
pbfile.close
def show_main_menu():
''' Show main menu for Phone List '''
print("\n *** Phone List Menu ***\n"+
"------------------------------------------\n"+
"Enter 1, 2, 3 or 4:\n"+
"1: Display Your Contacts Records\n" +
"2: Add a New Contact Record\n"+
"3: Search your contacts\n"+
"4: Delete a Contact Record\n"+
"5: Quit\n**********************")
choice = input("Enter your choice: ")
if choice == "1":
pbfile = open(phonebook, "r+")
file_contents = pbfile.read()
if len(file_contents) == 0:
print("Phone List is empty")
else:
print (file_contents)
pbfile.close
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
elif choice == "2":
enter_contact_record()
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
elif choice == "3":
search_contact_record()
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
elif choice == "4":
delete_contact_record()
user_entry = ("Please Enter to Return to Main Menu ...")
show_main_menu()
elif choice== "5":
print("Thanks for using Phone List")
else:
print("Wrong choice, Please Enter [1 to 5]\n")
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
I added the main menu above to show the menu of the phone book, there should be another choice to delete a contact.
The following code is to search for contact. It will show if a contact is already in the phone book but will mention not on record if there is no contact by the name they searched.
def search_contact_record():
''' This function is used to searches a specific contact record '''
contact_search = input("Enter First name to search for contact record: ")
contact_search = contact_search.title()
pbfile = open(phonebook, "r+")
file_contents = pbfile.readlines()
found = False
for line in file_contents:
if contact_search in line:
print("You searched for:", end=" ")
print (line)
found=True
break
if found == False:
print("There's no contact Record in Phone List with name = " + contact_search )
The next function is to enter contact and add it to the phonebook txt file created in the beginning.
def enter_contact_record():
''' It collects contact info firstname, last name, email and phone '''
first = input('Enter First Name: ')
first = first.title()
last = input('Enter Last Name: ')
last = last.title()
phone = input('Enter Phone number: ')
email = input('Enter E-mail: ')
contact = ("[" + first + " " + last + ", " + phone + ", " + email + "]\n")
pbfile = open(phonebook, "a")
pbfile.write(contact)
print( "This contact\n " + contact + "has been added successfully!")
#def delete_contact():
show_main_menu()
I got confused on the part how to delete the contact from the txt phonebook. Last delete lines I have trying was the following
def delete_contact_record():
#Initiate a name variable
contact_delete = input('Enter the name of the contact you wish to delete: ').title()
pbfile = open(phonebook, "r+")
file_contents = pbfile.readlines()
found = False
for line in file_contents:
if contact_delete in line:
confirm = input('Are you sure you wish to delete '+contact_delete+' y/n?: ')
print(confirm)
if confirm == 'y':
del phonebook[contact_delete]
found = True
if found == False:
print('That contact does not exist! Return to the main menu to enter the contact')
it works up to the line asking for confirmation y/n. But when I enter Y, I get a TypeError: 'str' object does not support item deletion
Thank you.
Your main problem is that your phone book is a flat file. As such, a deletion is "rewrite the entire file, but without the deleted record."
This is, needless to say, very inefficient.
You will also have problems in the future with spurious matches for searches, since contact_search in line is perfectly happy to match parts of names.
Personally, I'd recommend using an SQLite3 database instead of a flat file (SQLite3 support is built in to Python). SQLite3 databases are actually single files, but you can use almost all of the SQL language to perform structured queries, and let it manage the file for you.
If writing SQL is too daunting, the SQLAlchemy Python package can help by making database tables work like Python classes.

how to check if objedc has attribute false o true

I'm trying to check if any of the students are on probation and if they are, display which student please assist with the error code, the code is meant to check if anyone has violated probation, it also displays an error code, the except is normally key error, but when I was trying to figure out the problem i changed it to keyboard interrupt
if students[Student].is_on_probation:
KeyError: 0
students = {}
try:
while True:
from Student import Student
students['1'] = Student("Jim", "Business", 3.1, False)
viewing = False
viewingchange = input("Would you like to view something: ").lower()
if viewingchange == "y":
viewing = True
elif viewingchange == "yes":
viewing = True
else:
viewing = False
add = input("Would you like to add someone: ")
if add.lower() == "yes" or "y":
adder = str(input("Who would you like to add: "))
major = str(input("What is their major: "))
gpa = float(input("GPA: "))
is_on_probation = bool(input("is on probation: "))
students[str(len(students)+1)] = Student(adder, major, gpa, is_on_probation)
def checking():
if viewing:
checker = input("Would you like to view all students or student a/s: ")
if checker.lower() == "a":
print(students)
checkfor = input("Check for: ")
if checkfor.lower() == "probation":
for Student in range(len(students)):
print("works")
if students[Student].is_on_probation:
print("yeppp")
else:
pass
checkerdouble = False
elif checker.lower() == "s":
searchquery2 = input("And which attribute would you like to search: ")
test = input("Student ID: ")
dude = students[test]
if searchquery2.lower() == "Name".lower():
print(dude.name)
elif searchquery2.lower() == "Major".lower():
print(dude.major)
elif searchquery2.lower() == "GPA".lower():
print(dude.gpa)
elif searchquery2.lower() == "is on probation" or "iop" or "probation".lower():
print(dude.is_on_probation)
checkerdouble = True
checking()
except KeyboardInterrupt:
print("Error code: " + "45345593M3940249525")
Your students dictionary uses string representations of numbers that start at str(1). So the loop should do the same. I think it would be better to just use int keys.
for student_id in map(str, range(1, len(students)):
if students[student_id].is_on_probation:
print(student_id)
This would work but it relies on the dictionary keys being dense. I would prefer to do:
for student_id in sorted(students, key=int):
if students[student_id].is_on_probation:
print(student_id)
Some might object to the indexing, as one can do:
for student_id, student in sorted(students.items(), key=lambda v: int(v[0])):
if student.is_on_probation:
print(student_id)

Order generator program

I am trying to make a short program which will take user input, append the input to a list and then randomly determine the order of the elements in the list.
this is what I thought out:
from random import choice
participants = []
prompt = "\nPlease enter players first name: "
prompt += "\nPlease enter 'q' when all players have been entered: "
while True:
user = input(prompt)
if user == 'q':
break
print(f"There are {slot} participants")
else:
participants.append(user)
slot = len(participants)
print("\n\n")
for participant in participants:
print(f"{participant}")
print(f"So far, there are {slot} participants")
while participants:
for participant in participants:
person_of_choice = choice(participants)
person_in_question = participants.remove(person_of_choice)
print(person_in_question)
However, I am getting the following output
Mark Stark Dark So far, there are 3 participants
Please enter players first name: Please enter 'q' when all players
have been entered: q None None None
How do I change the ordering from none into their names?
I've changed a few things in the code, and the changes are commented out with ##.
you can try it to see the output.
from random import choice
participants = []
prompt = "\nPlease enter players first name: "
prompt += "\nPlease enter 'q' when all players have been entered: "
# init slot to zero
slot = 0
while True:
user = input(prompt)
if user == 'q':
print(f"There are {slot} participants")
## if you want to use `print` function before `break`,
## you must put the `break` statement under the `print` function
break
else:
participants.append(user)
slot = len(participants)
print("\n\n")
for participant in participants:
print(f"{participant}")
print(f"So far, there are {slot} participants")
while participants:
for participant in participants:
person_of_choice = choice(participants)
print(person_of_choice)
# person_in_question = participants.remove(person_of_choice)
## person_in_question is None, because `remove` always return None
## you can this from here https://docs.python.org/3/tutorial/datastructures.html
participants.remove(person_of_choice)

How to manage inventory: add, remove, modify/update , search, and print

sorry if this is not presented well. This is my first time ever using StackOverflow. I'm trying to create this to keep track of inventory. I do not know how to utilize try-excepts. Additionally, I don't know what else is going wrong. Thanks for any and all help !
data handler:
import os
class DataHandler():
def __init__(self, filename, datadict = {}):
self.filename = filename
self.datadict = datadict
def readData(self): # returns dictionary
try:
fileobj = open(self.filename,'r')
datastr = fileobj.read()
fileobj.close()
# return dictionary read from file or null dictionary
if datastr != '':
return eval(datastr)
else:
return self.datadict
except FileNotFoundError:
return self.datadict # null dictionary
def writeData(self, datadict): # must pass dictionary
fileobj = open(self.filename,'w')
fileobj.write(str(datadict))
fileobj.close()
separate file:
import DataHandler as DH
def menuDisplay():
print("="*40)
print("1 - Add inventory item")
print("2 - Modify inventory item")
print("3 - Delete inventory item")
print("4 - Print inventory list")
print("5 - Exit program")
print("="*40)
selection = input("\nPlease enter menu choice: ")
if selection < "1" and selection > "5":
input("Invalid selection, please enter 1 - 5")
menuDisplay()
else:
return int(selection)
def addItem(invDict,dh):
itemdesc = input("Item Description: ")
itemqty = int(input("Qty: "))
if len(invDict) > 0:
nextKey = sorted(invDict.keys())[-1]+1
else:
nextKey = 1
invDict[nextKey]=[itemdesc,itemqty]
dh.writeData(invDict)
def printInv(invDict):
print("{:<10}{:20}{:6}".format("Item #", "Description", "Qty",))
for dkey, lvalue in invDict.items():
print("{:<10}{:20}{:6d}".format(str(dkey), lvalue[0],lvalue[1], lvalue[2]))
def delItem(invDict,dh):
itemnum = input("Please enter item to delete: ")
del invDict[int(itemnum)]
dh.writeData(invDict)
# complete error checking
def modItem(invDict,dh):
itemnum = input("Please enter item to modify: ")
newqty = input("Please enter the new quantity: ")
invDict[int(itemnum)][1] = int(newqty)
dh = DH.DataHandler("inventory.txt")
invDict = dh.readData()
selection = 0
while selection != 5:
selection = menuDisplay()
if selection == 1:
addItem(invDict,dh)
elif selection == 2:
modItem(invDict,dh)
elif selection == 3:
delItem(invDict,dh)
elif selection == 4:
printInv(invDict)

Getting a Value Error When I Shouldn't Be

I'm trying to have my input move on when enter is pushed on a line with only spaces or just a blank, it doesn't work though it gives me a value error once before it gives me the proper return, which in turn seems to append an extra value to my array and screws over the entire program.
import math
def getItems():
quitNow = False
while not quitNow:
prepTotal = []
paintTotal = []
priceTotal1 = []
priceTotal1d = []
priceTotal2 = []
priceTotal2d = []
names = []
loopQuit = False
index = 1
while not loopQuit:
ans = raw_input("Enter a Name and press Enter to Continue\nEnter \"Q\" to Quit and get the Full Price: ")
if(ans.lower() != "q"):
innerLoopQuit = False
names.append(ans)
print "\nPlease enter your prep hours for " + names[index-1] + ": "
while not innerLoopQuit:
try:
inp = raw_input()
if(inp == ""):
innerLoopQuit = True
else:
float(inp)
prepTotal.append(float(raw_input()))
except ValueError:
print "Please enter a valid number."
You're calling raw_input() again in your else clause. Also, float(inp) doesn't really do anything if you don't assign it anywhere. prepTotal.append(float(inp)) is what you want to do.

Categories

Resources