This Is Quite Simple but I cant get the hang of it. I'm writing a short program where you enter the name, it will compare to each item in the array, then if it is found print what number it is in the array. if it isnt found, then enter a new name
Names = ['alice', 'bob', 'carol', 'david']
name = input("Enter Name ").lower()
c = 0
while name != Names[c]:
c = c + 1
if c == (len(Names)):
name = input("Name Not Found \n \nEnter Name ").lower()
c = 0
if name == Names[c]:
print ("name found, in position ", c)
It Always Comes Up With Name Not Found
name.lower without the () at the end will return the whole lower function and it will mess with the variable
So just replace that with name.lower() and it should work
Alternatively, you could use Name.index(name) and create a recursive function to search for names, like so:
Names = ['alice', 'bob', 'carol', 'david']
def findName():
name = input("Enter Name: ").lower()
if name in Names:
print(f'Name at position {Names.index(name)}')
else:
print('Name not found; try again')
findName()
findName()
Or the same code but in a loop:
while True:
name = input("Enter Name: ").lower()
if name in Names:
print(f'Name at position {Names.index(name)}')
break
else:
print('Name not found; try again')
Use name = input("Enter Name ").lower() instead of name = input("Enter Name ").lower.
name = input("Enter Name ").lower would assign name to the function lower, while name = input("Enter Name ").lower() runs the function lower and assigns name its return value
Related
This is part of my homework and the reason why I found posted this was because I was confused about what I'm doing wrong.
school = [['Abby Li'],
['Ella Wang', 'Danielle Han','Katherine Zhang', 'Morgan Liu'],
['Josh Li']
]
def searchStudent(school1, lastname1):
firstname = "Not"
lastname = "Found"
for grade in school1:
for student in grade:
name = student.split();
if name[1] == lastname1:
firstname = name[0]
lastname = name[1]
return firstname, lastname
while (True):
search = input("Please enter last name to search:")
if (search == "exit"):
break
foundFirst, foundLast = searchStudent(school, search)
print("found student: ", foundFirst, foundLast)
print("")
So this is my code, but whenever I enter "Li" as the last name, only Josh shows up and Abby doesn't. Can someone help me fix it? Thank you so much!
Also, here's the link for it if it doesn't show up above: code
Your indentation makes your if statement out of the for loop
Also if you want to print all the matches you need to store all of them, so you'll need something like list!
school = [['Abby Li'],
['Ella Wang', 'Danielle Han','Katherine Zhang', 'Morgan Liu'],
['Josh Li']
]
def searchStudent(school1, lastname1):
firstname = "Not"
lastname = "Found"
result = []
for grade in school1:
for student in grade:
name = student.split();
if name[1] == lastname1:
firstname = name[0]
lastname = name[1]
result.append([firstname, lastname])
return result
while (True):
search = input("Please enter last name to search:")
if (search == "exit"):
break
result = searchStudent(school, search)
for name in result: print("found student: ", name[0], name[1])
print("")
Please enter last name to search:Li
found student: Abby Li
found student: Josh Li
Please enter last name to search:exit
You have an indentation error:
for grade in school1:
for student in grade:
name = student.split();
if name[1] == lastname1:
firstname = name[0]
lastname = name[1]
Note that the if statement is outside the loop, after the loop.
Therefore, the only name it will check is that last one in the entire school list. To check all names, you have to indent it to the same level as that inner split command.
Also note that your return statement will return only that last name found. If you want to return more, you need to upgrade your logic.
You need to make a list of found students say:
found_students = []
and then append found names to it and then return that list
as of now 'Abby Li' is being overwritten by 'Josh Li'
I have no idea what I am doing wrong. Here is the question:
● Write a Python program called “John.py” that takes in a user’s input as a String.
● While the String is not “John”, add every String entered to a list until “John” is entered.
Then print out the list. This program basically stores all incorrectly entered Strings in a
list where “John” is the only correct String.
● Example program run (what should show up in the Python Console when you run it):
Enter your name :
Enter your name:
Enter your name:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
This is what I have so far:
name_list = [" "]
valid_name = "John"
name = str(input("please enter a name: "))
if name != valid_name.upper():
#name = str(input("please enter a name: ")
name_list.append(name)
name_list += name
elif name == valid_name.upper():
name_list.append(name)
name_list += name
print("Incorrect names that you have added: ")`enter code here`
print(name_list[0:])
You almost got it! just need to use a while loop instead of a if/else:
name_list = []
valid_name = "John"
name = str(input("please enter a name: "))
while name != valid_name:
name_list.append(name)
name = str(input("Incorrect! please enter a name: "))
print(f"Correct! Incorrect names that you have added: {name_list}")
im on the first part of my course work and im cleaning it up
i want to keep copying and pasting but i know looping it is time efficient and infinite
username = ["bob", "kye", "mes", "omar", "luke", "ben", "robin", "sam"]
name=str(input("whats name 1 "))
round=0
if name in username:
print(" p1 Authenticated")
name2=str(input("whats name 2 "))
if name2 in username:
print(" *STARTING GAME* ")
else:
print("Invalid User")
else:
print("Invalid User")
if you type and name not previously made it should loop like try again till a valid name is typed up
but if i type something wrong code continues and stops when they needs the name
This piece of code would ask for the name as many times needed until the user inserts the valid name.
name_one = ''
name_two = ''
usernames = ['bob', 'kye', 'mes', 'omar']
while name_one not in usernames:
name_one = input('Insert first name: ')
while name_two not in usernames:
name_two = input('Insert first name: ')
Another way would be:
names = []
usernames = ['bob', 'kye', 'mes', 'omar']
while len(names) < 2:
name = input('Insert name: ')
if name in usernames:
names.append(name)
else:
print('Invalid user, try again')
The second example you make a loop that is aways verifying if the list of names has at least two names if it does the loops breaks and the code continues. Then to access each name you use names[0] and names[1].
As commented by Patrick, you should try reading about loops.
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'm trying to make this so that when a person types their name just the initials display capitalized and separated by a period. I can't figure out what is wrong with this code I wrote... help pls!
def main():
name = input('Type your name and press ENTER. ')
name_list = name.split()
print(name_list)
first = name[0][0]
second = name[1][0]
last = name[2][0]
print(first,'.', second,'.')
main()
If you are on Python 2.x you should exchange input for raw_input. Here's a quicker way to achieve what you're aiming for assuming you're on Python 2.x:
def main():
full_name = raw_input('Type your name and press ENTER. ')
initials = '.'.join(name[0].upper() for name in full_name.split())
print(initials)
def main():
name = input('Type your name and press ENTER. ')
name_list = name.split()
print(name_list)
first = name_list[0][0]
second = name_list[1][0]
last = name_list[2][0]
print(first.upper(),'.', second.upper(),'.', last.upper())
main()
Here's a version similar to the one you have.
Note that you were using name instead of name_list, and some hard-coded indexes.
def main():
name = input('Type your name and press ENTER. ')
name_list = name.split()
for part in name_list:
print(part[0].upper() + ". ", end="")
print()
main()
It loops over the list you created with split(), and prints the first letter (in upper case) of each part of the name.
The loop only makes sense if you want every part to be included of course.
I'll try to explain why it occurred rather than just giving you the solution.
You're using name instead of name_list when name_list is what you're intending to use.
name for 'Amanda Leigh Blount' = 'Amanda Leigh Blount'
but name_list = name.split() = ['Amanda', 'Leigh', 'Blount']
So you get a difference in the two only on the middle/last name.
The first name is equivalent for both:
name[0][0] == name_list[0][0]
The left side matches the first letter of the first letter:
'Amanda Leigh Blount'[0][0] = 'A'[0] = 'A'
The right side matches the first letter of the first word.
['Amanda', 'Leigh', 'Blount'][0][0] = 'Amanda'[0] = 'A'
But for the second:
name[1][0] != name_list[1][0]
because the first & second are:
'Amanda Leigh Blount'[1][0] = 'm'[0] = 'm'
['Amanda', 'Leigh', 'Blount'][0][0] = 'Leigh'[0] = 'L'
So just use name_list instead of name:
first = name_list[0][0]
second = name_list[1][0]
last = name_list[2][0]