I am new to coding and have a list of lists that I need to search.
I want to see what lists contained in the larger list have the variable full_choice as the 3rd item in the sequence.
All lists that contain third_choice i need to print to a txt file.
the code below works and adds exactly what I need it to to the file, however I need the function to start again if there is no match for the variable full_choice.
def display_instructor_txt():
file_name = input('type in the name of the file you want to create do not include .txt')
file_name_full = file_name + '.txt'
new_file = open(file_name_full,'w')
first_choice = input('type in the first name of the instructor you want to filter by ')
last_choice = input('type in the last name of the instructor you want to filter by ')
full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I have tried inserting an else: at the end of the code however while that has ends up creating the file it doesn't write anything to it.
Tried to fix your indentation. I'm guessing you wanted something like this:
def display_instructor_txt():
file_name = input('type in the name of the file you want to create do not include .txt')
file_name_full = file_name + '.txt'
new_file = open(file_name_full,'w')
first_choice = input('type in the first name of the instructor you want to filter by ')
last_choice = input('type in the last name of the instructor you want to filter by ')
full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I just moved the else block forward to align with the if block you had a few lines before.
As #Haken Lid suspected, please fix indentation:
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').
replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
Related
I'm learning Python and I'm wondering how you would insert a name into a list and for it to be held in that variable so the script can identify if it's seen you before.
Any help would be much appreciated
# Default People Already In List at program start
list = ['Bob','Jim',]
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in list:
print("Nice to meet you again" + Name)
else:
list.insert(0, Name)
print("Hi " + Name + ", Nice too meet you for the first time.")
# Troubleshoot
print(list)
Your should rename your variables - here a short correction of your code, although it is looking good already! I changed the insert to append as well!
But it will obviously forget since the list is always initialized with Bob and Jim in it, and then you ask for the name - if is not Bob or Jim, it is new and therefore appended. But then your program ends, so when you start it new, your list is only populated with Bob & Jim again. You could put the whole construct in a "while True" construct to make the same question multiple times until you dont want to anymore!
EDIT: included the while (you can enter it numerous times if you just press "Enter" for the question! and put the list in the beginning, so it will not be initialized every time you run a new name! and important: if you see someone for the first time, include the print in the else-clause, otherwise it will be printed everytime, even if you saw the name before!
name_list = ['Bob','Jim']
while True:
print("Hello, What\'s your name? ")
input_name = input("Enter your Name: ")
if str(input_name) in name_list:
print("Nice to meet you again, " + input_name)
else:
name_list.append(input_name)
print("Hi " + input_name + ", Nice too meet you for the first time.")
# Troubleshoot
print(name_list)
if str(input("Another name? ")) == '':
continue
else:
break
This is what I did. This works with a CSV file.
# Load from file
list = []
listfile = open('list.csv', 'r+')
for name in listfile:
list.append(name[:-1])
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in list:
print("Nice to meet you again " + Name)
else:
print("Hi " + Name + ", Nice too meet you for the first time.")
listfile.write(Name + "\n") #adding to file
# Troubleshoot
print(list)
This will store it to a file, also its not a good practice to use built in functions and utilities as variable names. so I modified the name as lists
try:
with open("listofnames.txt","r") as fd:
lists=eval(fd.read())
except:
lists=[['Bob','Jim',]]
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in lists:
print("Nice to meet you again", Name)
else:
lists.insert(0, Name)
with open("listofnames.txt","w") as f:
f.write(str(lists))
print("Hi " + Name + ", Nice too meet you for the first time.")
# Troubleshoot
print(lists)
The purpose of this program is to create a list of names for people attending a party. I would like to be able to grant the user the ability to continue adding names until they chose YES as an option to exit the loop. However, I have am stomped when it comes to having them enter a name they would like to remove in case they added someone by accident or if they would like to edit the list and remove or replace someone.
I am currently a newbie to programming, hence the lack of classes to this code. Any help would be greatly appreciated. Thank you all in advance!
#Initialize empty list
partyList = []
#Initilize empty entry
inviteeName = ''
endEntry = ''
#Run loop until YES is entered as a value
while endEntry != "Yes":
inviteeName = input("Please enter the name of the person you are inviting below." + "\nName: ")
inviteeName = inviteeName.title()
# Verifies if a name was not entered.
while inviteeName == "":
inviteeName = input("\nPlease enter the name of the person you are inviting below." + "\nName: ")
inviteeName = inviteeName.title()
endEntry = input("\tPress ENTER to continue or type Yes to finish: ")
endEntry = endEntry.title()
#Append every new name to the list
partyList.append(inviteeName)
#Adds the word "and" to finish sentence if there are more than one invitees. NOTE: Make a class please!
numOfInvitees = len(partyList)
if numOfInvitees > 1:
partyList.insert(-1, 'and')
#Remove brackets and quotes.
partyList = ', '.join(partyList)
#Print message
print("\nThis will be your final message:\n" + str(partyList) + "\nYou are invited to my party!\n")
I was trying to use this to assist the user with removing names entered by accident.
submit = input('Submit?: '.title())
submit = submit.title()
if submit == 'Yes':
print('Invite has been sent!')
elif submit == 'No':
remNameConfirmation = input('Would you like to remove a name from the list?: ')
remNameConfirmation = remNameConfirmation.title()
if remNameConfirmation == 'Yes':
uninviteName = (input('Who would you like to remove?: '))
uninviteName = uninviteName.title()
Here is the line that is giving some trouble
partyList.remove(uninviteName)
print(partyList)
When your code reaches
partyList = ', '.join(partyList)
it will set the variable partyList to a string. Since it is no longer a list it does not have the .remove method.
I have got it to work, except the list doesn't save the inputs properly; it just lists them as three periods. This is the code:
names = []
i=0
while 1:
i+=1
name=input("Please enter the name")
if name==" ":
break
names.append(names)
print(names)
Change names.append(names) to names.append(name), since you want to append name to the list names (just a typo I guess).
Also if name == " " must be changed to if name == "", since if the user presses enter without providing any name, the input is an empty string, not a white space.
Correct code here:
names = []
i = 0
while True:
i += 1
name = input("Please enter the name ")
if name == "":
break
names.append(name)
print(names)
I am having trouble getting past writing user input to my list what am I doing wrong here? This is an address book program that I am writing, the assignment is to create parallel lists that will store user input data in the appropriate list using a for or while loop. The program must also have a search function which you can see is at the bottom of the code. My issue that I am having is getting the program to store data within my lists. Unfortunately lists are something that give me lots of trouble I just cant seem to wrap my head around it no matter how much research I have done. The issue im running into is the append.data function when trying to write lastname and firstname to my list of names. what am I doing wrong?
#NICHOLAS SHAFFER
#5/11/2016
#MYADDRESSBOOK
def menu():
index = 0
size = 100
count = 0
answer = raw_input("Are You Creating An Entry [Press 1] \nOr Are You Searching An Entry [Press 2] ")
if answer == "1" :
print ("This is where we create")
append_data(index, size, count)
elif answer == "2" :
print ("this is where we search")
search_database()
name[size]
phone[size]
addresss[size]
# IF we are creating
def append_data(index, size, count):
# collect information
for index in range(0, 100):
optOut = 'no'
while optOut == 'no':
lastname[count] = raw_input("What is the persons last name? ")
firstname[count] = raw_input("What is the persons first name? ")
phone[count] = raw_input("What id the persons phone number? ")
address[count] = raw_input("What is the persons address? ")
count = count + 1
print 'Would you like to create another entry?'
optOut = raw_input('Would you like to create another entry? [ENTER YES OR NO]:')
if optOut == 'yes':
menu()
#create string to print to file
#print temp1
#print (firstname + " " + lastname + ", " + phone + ", " + email + ", " + address)
print listName[index]
print listPhone[index]
print listAddress[index]
print 'file has been added to your addressbook sucessfuly'
menu()
# SEARCHING FOR A RECORD
def search_database():
searchcriteria = raw_input("Enter your search Criteria, name? phone, or address etc ")
print searchcriteria
if searchcriteria == "name":
temp1 = open(listName[lastname, firstname],"r")
print temp1
if searchcriteria == "phone":
temp1 = open(listPhone[0], "r")
print temp1
if searchcriteria == "address":
temp1 = open(listAddress[0], "r")
print temp1
else:
print "sorry you must enter a valid responce, try again."
menu()
for line in temp1:
if searchcriteria in line:
print line
errorMessage()
# USER DID NOT PICK CREATE OR SEARCH
def errorMessage():
print ("Incorrect Answer")
exit()
menu()
Your error message says it all:
line 34, in append_data lastname[count]... NameError: global name 'lastname' is not defined
You'll get this same error if you type lastname[4] in any interpreter -- you've simply never defined a list called lastname, so you can't access items in it. In the short term, you can fix this with a line
lastname = list()
You're going to end up with more troubles though; lastname won't be accessible outside the function where you define it, neither will listName. I'd probably approach that by writing them into a data file/database, or maybe creating a quick class whose members will all have access to self.lastname.
My final append for lists thanks again Noumenon
def append_data(index, size, count):
lastnames = list()
if count < size -1:
lastname = raw_input("What is the persons last name? ")
lastnames.append(lastname)
print lastnames
firstnames = list()
if count < size - 1:
firstname = raw_input("What is the persons first name? ")
firstnames.append(firstname)
print firstnames
phones = list()
if count < size - 1:
phone = raw_input("What id the persons phone number? ")
phones.append(phone)
print phones
addresss = list()
if count < size - 1:
address = raw_input("What is the persons address? ")
addresss.append(address)
print addresss
listName = (lastnames, firstnames)
addressbook =(listName, phones, addresss)
index = index + 1
count = count + 1
print addressbook
optOut = raw_input('Would you like to create another entry? [Enter YES or NO]: ')
if optOut == 'YES':
menu()
print 'file has been added to your addressbook sucessfuly'
menu()
I have been testing my code for the past few hours and I am stumped. This program takes a text file of names, turns the names into a list, prints the names, sorts the names, prints the sorted names, then allows you to search through the list. Everything seems to be working fine, but the one issue I have is exiting the while loop. If y or Y is selected you can search again, but that also happens if anything else is selected. I added a print statement outside the loop so if anything other than y is selected then the program should end with that last printed string, but it doesn't seem to be working. Does anyone have any ideas about why it isn't working and what I could change to get it to work?
Thank you for your time.
#define the main function
def main():
#create a variable to control the loop
keep_going = 'y'
#setup loop to search for name
while keep_going == 'y' or keep_going == 'Y':
#call input name function
names = input_name()
#call print name function
print_name(names)
#sort the printed list
names.sort()
#call the print name function
print_name(names)
#call the output name function
output_name(names)
#call the search name function
search_name(names)
#add user input for another search
search_again = input('Would you like to make another search?(y for yes): ')
#print if anything other than y or Y is selected
print()
print('Goodbye!')
#define the input function
def input_name():
#open the names.txt file
infile = open('names.txt', 'r')
#read contents into a list
names = infile.readlines()
#close the file
infile.close()
#strip the \n from each element
index = 0
while index < len(names):
names[index] = names[index].rstrip('\n')
index += 1
#return the list back to main function
return names
#define the print name function
def print_name(names):
#print the contents of the list
for name in names:
print(name)
#define the output name function
def output_name(names):
#open file for writing
outfile = open('sorted_names.txt', 'w')
#write the list to the file
for item in names:
outfile.write(item + '\n')
#close the file
outfile.close()
#return to main function
return
#define the search name function
def search_name(names):
#add a user input to search the file
search = input('Enter a name: ')
#determine whether the name is in the list
if search in names:
#get the names index
name_index = names.index(search)
#print the name was found and give the items index
print(search, "was found in list. This item's index is", name_index)
else:
#print the item was not found
print(search, 'was not found in the list.')
main()
#create a variable to control the loop
keep_going = 'y'
#setup loop to search for name
while keep_going == 'y' or keep_going == 'Y':
#add user input for another search
search_again = input('Would you like to make another search?(y for yes): ')
You never set keep_going to something else. Instead, you ask the user to enter y to continue but store it in search_again (which is then thrown away). You will want to change that to store the value in keep_going.
You are testing keep_going, but setting search_again
Replace line 29 which states:
search_again = input('Would you like to make another search?(y for yes): ')
with the following:
keep_going = input('Would you like to make another search?(y for yes): ')
Because when you enter y or Y then you are defining the variable search_again to that letter not the variable keep_going which is needed to change for the loop to stop.