Order generator program - python

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)

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.

Creating a menu using a dictionary

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)

comparing user input to a dictionary in python

I have to create a program that lets a user input what courses they have taken(one at a time), and compare it to a dictionary of "courses" with the pre-requisites and print what courses that student is eligible to take. I am not sure on how to compare the user input to the dictionary to print what courses they can take. Here is what I have so far
print "Enter a course(0 to quit): "
courses = raw_input()
d = {150:[150],
161:[161],
162:[161],
231:[162],
241:[161],
251:[251],
260:[150],
300:[241],
303:[162],
304:[162],
307:[162],
353:[231],
385:[353],
355:[231],
461:[303,304,307,231],
475:[303,304,307],
480:[470]
}
while courses =! '':
if courses in d.keys():
print("You have taken: ", courses)
if courses == 0:
break
You are only getting input once. You need to get input in a loop:
d = {150:[150],161:[161],162:[161],231:[162],241:[161],251:[251],260:[150],300:[241],303:[162],304:[162],307:[162],353:[231],385:[353],355:[231],461:[303,304,307,231],475:[303,304,307],480:[470]}
prereqs = set()
while True:
course = int(raw_input("Enter a course you have taken (0 to quit): "))
if course == 0:
break
try:
prereqs.update(d[course])
except KeyError:
print '\t\t\t\t\tHmm...I don\'t know that course'
In the while loop, we are getting input every iteration. If it is 0, we break out of the loop. If not, we try to lookup the course in the dict. If this fails, we print the "error" message. You should be able to take it from here(prereqs stores the courses that you have took in a set).

Printing function values while returning with main loop

I am writing a code for student record... This is what i've tried
def std1():
stud=input('Enter Student name')
crs=[]
crst=int(input('How many courses you want to enter'))
for i in range(crst):
EnterCourse = input('Course')
crs.append(str(EnterCourse))
stdrec1=(stud,crs)
return main()
def std2():
stud=input('Enter Student name')
crs=[]
crst=int(input('How many courses you want to enter'))
for i in range(crst):
EnterCourse = input('Course')
crs.append(str(EnterCourse))
stdrec2=(stud,crs)
def main():
print("""
Welcome to the Student Database
[1] = Enter Student Record
[2] = Enter Second Student Record
[3] = Enter Third Student Record
[4] = Print the record
""")
action = input('What Would you like to do today? (Enter number to Continue) ')
if action == '1':
std1()
elif action == '2':
print('2')
elif action == '3':
print('3')
elif action == '4':
print(#all the list together)
else:
print('Error! Wrong Menu Selected | Calling the FBI now')
How can i make all the tuples print together when the option 4 is selected which are currently inside their own function and in case user hasn't work on a 2nd option for example. it will print like this
First student --- Name , [courses]
2nd student ----- You haven\t't entered anything
Do you want to enter Y or N
Y will return that function and N will stop the function.
and after input data in each option how will it return the main function again so user can re-select the options

Python: TypeError: list indices must be integers or slices, not list

Ok I have completely changed my code now so that the customers lists are inside another list. Now I am trying to refer to the individual lists for each customer with a for loop. But when I am trying to access individual values in the customer lists I am getting a TypeError: list indicies must be integers or slices, not list. Here is the code:
customers = [ ]
customers.append(["Bilbo","Baggins","Dodge Dart", "120876","March 20 2017"])
customers.append(["Samwise"," Gamgee","Ford Tarus","190645","January 10 2017"])
customers.append(["Fredegar","Bolger","Nissan Altima", "80076","April 17 2017"])
customers.append(["Grima"," Wormtounge","Pontiac G6", "134657", "November 24 2016"])
customers.append(["Peregrin"," Took","Ford Focus", "143567", "February 7 2017"])
customers.append(["Meriadoc","Brandybuck","Ford Focus", "143567", "February 19 2017"])
print("At Holden's Oil Change we use our custom built Python program to keep \
track of customer records \
and to display our company logo!!")
time.sleep(7)
print("Select and option from the menu!")
QUIT = '4'
COMMANDS = ('1','2','3','4')
MENU = """1 Current Customers
2 New Customers
3 Company Logo
4 Quit"""
def main():
while True:
print(MENU)
command = realCommand()
commandChoice(command)
if command == QUIT:
print("Program Ended")
break
def realCommand():
while True:
command = input("Select an option: ")
if not command in COMMANDS:
print("That is not an option!")
else:
return command
def commandChoice(command):
if command == '1':
oldCust()
elif command == '2':
newCust()
elif command == '3':
Turt()
def oldCust():
print("%6s%12s%20s%24s%22s" % ("First Name", "Last Name", "Car Make & Model", "Mileage Last Service", "Date Last Oil Change"))
for i in customers:
print("%8s%18s%22s%24s%32s" % (customers[i][0],customers[i][1],customers[i][2],customers[i][3],customers[i][4]))
the function oldCust() is where the error comes up when the for loop runs it is giving the type error. I've tried it several different ways but each ways sends back the same error.
Here is the whole error that gets returned:
Traceback (most recent call last):
File "C:\Users\hdaug\Documents\Holden's Personal\Spring 2016-2017\CSCI 1121\HoldensOilChange.py", line 264, in <module>
main()
File "C:\Users\hdaug\Documents\Holden's Personal\Spring 2016-2017\CSCI 1121\HoldensOilChange.py", line 49, in main
commandChoice(command)
File "C:\Users\hdaug\Documents\Holden's Personal\Spring 2016-2017\CSCI 1121\HoldensOilChange.py", line 66, in commandChoice
oldCust()
File "C:\Users\hdaug\Documents\Holden's Personal\Spring 2016-2017\CSCI 1121\HoldensOilChange.py", line 79, in oldCust
print("%8s%18s%22s%24s%32s" % (customers[i][0],customers[i][1],customers[i][2],customers[i][3],customers[i][4]))
TypeError: list indices must be integers or slices, not list
First of all use list to store customer variables. Then you can easily add new customer in the list.
Here is the complete solution of your problem:
"""
Program that is used to store service
records for prior customers or prompt
user for customer information for new customers.
The program also uses Turtle Graphics to display
the company logo.
"""
#Import time module for delays in program
import time
#Define current customers
customer_list = []
customer_list.append(["Bilbo","Baggins","Dodge Dart", "120876","March 20 2017"])
customer_list.append(["Samwise"," Gamgee","Ford Tarus","190645","January 10 2017"])
customer_list.append(["Fredegar","Bolger","Nissan Altima", "80076","April 17 2017"])
customer_list.append(["Grima"," Wormtounge","Pontiac G6", "134657", "November 24 2016"])
customer_list.append(["Peregrin"," Took","Ford Focus", "143567", "February 7 2017"])
customer_list.append(["Meriadoc","Brandybuck","Ford Focus", "143567", "February 19 2017"])
#Announce the company and what our program does
print("At Holden's Oil Change we use our custom built Python program to keep \
track of customer records \
and to display our company logo!!")
time.sleep(7)
#Tell the user what to do
print("Select and option from the menu!")
#Make the menu and menu options for the user
QUIT = '4'
COMMANDS = ('1','2','3','4')
MENU = """1 Current Customers
2 New Customers
3 Company Logo
4 Quit"""
#Define how the menu works if quit option selected
def main():
while True:
print(MENU)
command = realCommand()
commandChoice(command)
if command == QUIT:
print("Program Ended")
break
#Define what happens if a invalid command is entered or a correct command is entered
def realCommand():
while True:
command = input("Select an option: ")
if not command in COMMANDS:
print("That is not an option!")
else:
return command
#Command selection and running
def commandChoice(command):
if command == '1':
oldCust()
elif command == '2':
newCust()
elif command == '3':
Turt()
#Runs old customer selection
def oldCust():
#Print list of customers for the user to select from.
print("%6s%12s%20s%24s%22s" % ("First Name", "Last Name", "Car Make & Model", "Mileage Last Service", "Date Last Oil Change"))
for customer in customer_list:
for value in customer:
print(value,end="\t")
print("")
#Request response from user and define what happens depending on the input.
response = input("Ener a customers last name from the list: ")
customer_search_result = 0
for customer in customer_list:
if response.lower() == customer[1].lower():
user_milage = input("Enter current vehicle mileage: ")
user_date = input("Enter todays date (Month Day Year Format): ")
print("%6s%12s%20s%24s%22s" % ("First Name", "Last Name", "Car Make & Model", "Mileage Last Service", "Date Last Oil Change"))
print("%9s%13s%19s%25.9s%34s" % (customer[0], customer[1], customer[2], customer[3], customer[4]))
print("Have a great day!")
customer_search_result=1
if customer_search_result==0:
print("That is not a current customer!")
time.sleep(2)
#Request user input wheter they want to input new customer info or try another customer name.
nonCustResponse = input("Choose 1 to re-enter customer name or 2 to enter new customer info: ")
#if statement that decides what to do with the user input
if nonCustResponse == "1":
oldCust()
elif nonCustResponse == '2':
#Send the user to the newCust function if they enter a non-current customer
newCust()
#If the customer enters an invalid option the program restarts
else:
print("That is not an option. Program restarting")
time.sleep(3)
#Prompts user for information for the new customer
def newCust():
#Make an empty list for the new customer to be assigned to
new_customer = [" "," "," "," "," "]
#Request user input for the new customer information
new_customer[0] = input("Enter the customers firsts name: ")
new_customer[1] = input("Enter the customers last name: ")
new_customer[2] = input("Enter the customers vehilce (Make Model): ")
new_customer[3] = input("Enter the vehicle mileage: ")
new_customer[4] = input("Enter today's date (Month Day Year): ")
print("%6s%12s%20s%24s%22s" % ("First Name", "Last Name", "Car Make & Model", "Mileage Last Service", "Date Last Oil Change"))
print("%8s%13s%22s%25s%34s" % (new_customer[0], new_customer[1], new_customer[2], new_customer[3], new_customer[4]))
customer_list.append(new_customer)
if __name__=='__main__':
main()
I have updated some part of your original code to make it run able. This code can be improvised.
You can allow some escape code when you have finished your input, i.e. just empty string:
customers = []
new_customer = input('> ')
while new_customer:
customers.append(new_customer)
new_customer = input('> ')
So when the user has hit enter without writing anything, the input is done. If you want to change that 'exit code' to something more sophisticated, use this:
customers = []
exit_code = 'stop'
new_customer = input('> ')
while new_customer != exit_code:
customers.append(new_customer)
new_customer = input('> ')
To save an input to multiple vars, do something like this:
tmp = raw_input(">>> ")
var1 = tmp
var2 = tmp
var3 = tmp
To use an input multiple times, use a function:
def function(num):
i = 0
while i < num:
tmp = raw_input(">>> ")
function(3)
var1 = tmp
var2 = tmp
var3 = tmp

Categories

Resources