Learning lists and arrays and I am not sure where I went wrong with this program. Keep in mind I am still new to python. Unsure if i am doing it right. Ive read a few tutorials and maybe Im not grasping list and arrays. Ive got it to where you can type a name but it doesnt transfer to a list and then i get list is empty constantly as well as other errors under other functions in the code.
def display_menu():
print("")
print("1. Roster ")
print("2. Add")
print("3. Remove ")
print("4. Edit ")
print("9. Exit ")
print("")
return int(input("Selection> "))
def printmembers():
if namelist > 0:
print(namelist)
else:
print("List is empty")
def append(name):
pass
def addmember():
name = input("Type in a name to add: ")
append(name)
def remove():
pass
def removemember():
m = input("Enter Member name to delete:")
if m in namelist:
remove(m)
else:
print(m, "was not found")
def index():
pass
def editmember():
old_name = input("What would you like to change?")
if old_name in namelist:
item_number = namelist.index(old_name)
new_name = input("What is the new name? ")
namelist[item_number] = new_name
else:
print(old_name, 'was not found')
print("Welcome to the Team Manager")
namelist = 0
menu_item = display_menu()
while menu_item != 9:
if menu_item == 1:
printmembers()
elif menu_item == 2:
addmember()
elif menu_item == 3:
removemember()
elif menu_item == 4:
editmember()
menu_item = display_menu()
print("Exiting Program...")
For starting out, you've got the right ideas and you're making good progress. The main problem is how you defined namelist = 0, making it a number. Instead, namelist needs to be an actual list for you to add or append anything to it. Also, you're append() method is not necessary since once you define namelist as a list, you can use the built-in list.append() method, without having to write your own method.
So here are a few suggestions/corrections, which once you have the basis working correctly, you should be able to work out the rest of the bug fixes and logic.
Since you don't have any main() method, you can define namelist on
the first line of code, before any other code, so that it is
referenced in each method:
namelist = [] # an empty list
Change addmember() method to:
def addmember():
name = raw_input("Type in a name to add: ")
namelist.append(name)
Since namelist is a list, we can use the built-in len() method on nameslist to check if it's empty when printing out its contents (if any):
def printmembers():
if len(namelist) > 0: # Get the length of the list
print(namelist)
else:
print("List is empty")
Now that the Add() menu option is working for adding a name to the namelist, you should be able to implement removing, and editing names to the list using similar logic.
You should consider initializing the list to be empty instead of zero (unless you want that element).
namelist = list()
Also, your append method does not perform any actions. It's also pretty unnecessary since you can just use the append method of list.
def addmember():
name = input("Type in a name to add: ")
namelist.append(name)
If you did want to make your own append method you should understand that the variables in the function definition are inputs, so just saying def append(name) won't perform any action. In this case name is the identifier you are applying to the input argument. You could just as easily call it anything you wanted. A good way to understand this is by assigning the argument a different variable name than the one you pass it. Like this:
def append(nameToAppend):
namelist.append(nameToAppend)
You can call your append method in addmember like this:
def addmember():
name = input("Type in a name to add: ")
append(name)
After getting name from input, you call the append(name) method, yet your append method doesn't do anything yet.
In your append method you have to add the name you get to your namelist, like how you do in the editmember method.
Related
I am new to Python. Working with 2.7 for class.
The teacher set a project in which we are to code a program that takes a piece of a Monty Python script (input by user), stores it in a list of lists, replaces a specific name in the script with the user's name and prints the revised script out to console.
The issue I am running into is in my third function replace_name, the parameters are the list of lists, old name, new name.
However, I am getting
NameError:'word_list' is not defined
I understand that if a variable is not defined in the Main then it is local to its function.
I thought though, that by using return in the function that that information is stored to be used by subsequent functions.
Am I wrong?
def new_name(): #prompts for user's name. checks if input is valid
while True:
name = raw_input("Please enter your name.\n")
if len(name) < 1:
print "Invalid, please enter your name.\n"
else:
return name
def orig_script():#reads in script, splits into list of lists
word_list = []
script = raw_input("Please enter script, one line at a time. Enter 'done' to exit. \n")
if len(script) < 1:
print "Empty text field. Please try again.\n"
while script != 'done':#splits string input,adds to list
words = script.split()
word_list.append(words)
script = raw_input("Please enter script, one line at a time. Enter 'done' to exit.\n ")
if len(script) < 1:
print "Empty text field. Please try again.\n"
return word_list
def replace_name(word_list,old_name,new_name):#replaces old name with new name in list. creates new list from changes.
new_list = []
for sentences in range(word_list):
sentence = word_list[sentences]
for words in range(sentece):
word = sentence[words]
if word == old_name:
sentence[words] == new_name
new_list.append(sentence)
print new_list#debugging-change to return
new_name()
orig_script()
replace_name(word_list, Robin, new_name)
If my indentation is a bit off here, I apologize.
I tried to correct it from the copy/paste.
There are no indentation errors given in repl.it.
Traceback (most recent call last):
File "python", line 45, in <module>
NameError: name 'word_list' is not defined
You did not assign any of the word_list, Robin, new_name variables. Returning a variable of a particular name does not bind it to any type of external variable on its own, especially not one of the same name.
For example, you need to assign the return value explicitly to its own variable.
word_list = orig_script()
name = new_name()
replace_name(word_list, "old name", name)
Also
for sentences in range(len(word_list)):
sentence = word_list[sentences]
Is the same as
for sentence in word_list:
Note: You do have a typo in sentece and this is a comparison, not an assignment sentence[words] == new_name
Bonus, I think you can rewrite replace_name as
def replace_name(word_list,old_name,new_name):
return [[new_name if w == old_name else old_name for w in sentence] for sentence in word_list]
Pass the parameter in you function argument.
Ex.
#take the o/p of variable in another one and pass in funcation
return_val = orig_script()
old_name = ["jack", "mike" , "josh"]
new_name= ["jen" , "ros" , "chan"]
#calling replace name funcation
replace_name(return_val,old_name,new_name)
I'm really new to Python and I'm mainly just messing around. I'm trying to put together a function that validates a user input (in my case, to check wether the user writes either James or Peter. This is probably a very newbie question, but I was just wondering if my code is a good way to accomplish this function.
Thanks for any help.
namelist = "Peter", "James"
def nameinput():
global name
name = raw_input("Write a name. ")
def checkname(x):
while name not in namelist:
print "Try again"
nameinput()
else:
print "Good,", name
checkname(nameinput())
if name == "Peter":
print "This is a text for Peter"
elif name == "James":
print "This is a text for James"
No; there is no reason to use global variables here. Pass data around to the functions that need it.
def nameinput():
return raw_input("Write a name. ")
def checkname(name):
namelist = ["Peter", "James"]
while name not in namelist:
print "Try again"
name = nameinput()
else:
print "Good,", name
return name
name = checkname(nameinput())
Using global variables is generally frowned upon (it can really do stupid stuff if you don't always know what you are doing), so don't start doing so that early.
You could easily avoid that by returning the name from nameinput.
Also, you already have the name list. Do the following in the end:
if name in namelist:
print("This is a text for " + name)
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.
I'm teaching myself Python and writing a simple GPA calculator. I have very little programming experience prior other than a college Java course, so bear with my code.
The premise is, the code will ask if you want to add a course to the list. If you do, it runs a function asking you the class name. Every time you add a class it'll ask if you want to add another. If you don't, it'll spit out a list of the classes you've added and then ask you to enter in the grades. I didn't get the grading part done yet. I don't think that will be too hard.
The problem is you can add a bunch of classes and it will only spit out the last one you entered. I'm assuming the issue is in askAgain(): classList = addClasses() because it keeps overwriting, but I'm not sure how to avoid a global variable (since they're bad?) and still keep this from overwriting itself. I seem to draw a blank when trying to figure out how to call something once to intialize it and not run it again. I've also read that conditional variables are bad, so I'm not sure what's best practice here. thanks
def main():
askAgain()
return 0
def askAgain():
while True:
addOrNot = raw_input("Add a class? [y/n]: ")
if addOrNot == "Y" or addOrNot == "y":
classList = addClasses() #This is probably where my issue is.
else:
try:
editClassGradeSelection = mainMenu(classList)
addGrades(editClassGradeSelection, classList)
except:
print("Hey you didn't add any classes yet.")
def addClasses():
try:
if classList in locals():
print("debug msg - classList exists")
except:
classList = []
classList.append(raw_input("Add class to the list: "))
return classList
def mainMenu(classList):
print("Here are the classes you've added: ")
counter = 0
for classes in classList:
print((str(counter+1)) + ". " + (str(classList[counter])) + "\n")
counter = counter + 1
while True:
editGrade = raw_input("Enter the number for the class grade to edit: ")
if int(editGrade) > len(classList) or int(editGrade) < 1:
print("Enter a proper number in the range listed.")
else:
break
return editGrade
def addGrades(editClassGradeSelection, classList):
print("debug stuff for now: ")
print((str(editClassGradeSelection)))
print((str(classList[:])))
if __name__ == '__main__':
main()
Although this snippet makes sure classlist is defined:
try:
if classList in locals():
print("debug msg - classList exists")
except:
classList = []
classlist is a local variable, hence everytime you run that function, classlist will be [], which probably explains why you can't ever display more than one. The classlist you assign it to gets reassigned to the one element of classlist (addClasses scope) every time this line is called:
classList = addClasses() #This is probably where my issue is.
I have been trying to figure this out for way too long! What to do?
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return(submission)
name = input("What is your name?")
(fallBack(name))
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
I keep having the last input just print out nothing...
You need to store the result of fallBack().
Also, change fallBack() to return the original value if it is non-null:
def fallBack(submission):
if not submission:
return "fixed!"
else:
return submission
Then, use it like this:
name = fallBack(input("What is your name?"))
Just remove the brackets around fallBack(name)
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return submission
name = input("What is your name?")
name = fallBack(name)
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
Also remember that if using python 2.7 you should use raw_input instead of input
I'm not sure what you want to do, but I think this would do it:
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return (submission)
name = input("What is your name?")
name = fallBack(name)
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
Your two mistakes were not to return anything in case there is nothing to fix, and not to assin the value returned by the function.
By the way, there is a much more idiomatic way of doing this in Python:
name = input("What is your name?")
name = name or 'fixed!'
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
The second line tests if converting name to a boolean, and, if it returns False (for a string, it is equivalent to testing if it is not empty), replace it with 'fixed!'
The return is not well aligned! You are not returning anything unless submission is empty! :-)
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return(submission)