Fixing python code that doesn't show both values - python

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'

Related

Trying to get multiple input from user. Int + Str

Im new to coding in python, and is trying to make this work.
if input from user is "name age" it works just fine. But I want it to work if user inputs either (name+age) or (name+lastname+age). If I input 3 values I get ValueError: too many values to unpack (expected 2)
and if add name, lastname, age, =map(str, sys.stdin.readline().split()) to the code. I get a not enough values error when user input name+lastname+age
Hopefully someone can help me :)
name, age, =map(str, sys.stdin.readline().split())
age = int(age)
if "Paul" in (name):
result1 = (age*2)
print("Answer is", + result1)
Here's a possibility - read the input line without the map, parse it, and then differentiate the input based on the number of elements in the resulting list,
import sys
entry = sys.stdin.readline()
entry = entry.strip().split()
if len(entry) == 2:
# Name + age
name = entry[0]
age = int(entry[1])
print(name, age)
elif len(entry) == 3:
# Name + last name + age
name = entry[0]
last_name = entry[1]
age = int(entry[2])
print(name, last_name, age)
else:
raise ValueError('Wrong input arguments')
if "Paul" in (name):
result1 = (age*2)
print("Answer is", + result1)
If the input is nothing of the expected, this code raises an exception. You can instead keep prompting the user until they enter the right values. If you decide to keep the exception approach, consider using a more informative exception message.
Instead of trying to unpack the result of split() into two variables, you can use join() combined with list slicing to join everything but the last value into one (the name):
user = input().split()
age = int(user[-1])
name = ' '.join(user[:-1])
if "Paul" in name:
print(f"Answer is {age*2}")
This works regardless of how many "words" are in the name:
Paul McCartney 42
Answer is 84
Pauline 42
Answer is 84
Paul W. S. Anderson 42
Answer is 84
You can't split something into a dynamic number of variables this way.
Instead you need to capture the input and then work out how many fields were passed in. Something like:
user = map(str, sys.stdin.readline().split())
lastname = ''
name = user[0]
age = user[1]
if len(user) == 3:
lastname = user[1]
age = user[2]

Listing names still the correct one is quess

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}")

Nea login part loop?

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.

What is the best way to combine various object and print them out accordingly?

So I am attempting to write a program in Python that builds a list of students and eventually prints them out to the screen. For each student the user chooses to add, the input of first name, last name, and ID number are taken.
My issue is that although I am attempting to append each new person created onto a list called studentList[], when I print the list out at the end, I get an output of the correct number of student but all containing the same information as the last student I entered.
For example, if I add the students 'Johnny Tsunami 4', 'Billy Bobblie 23', 'Biggus Dickus 77', my output will read:
Biggus Dickus 77
Biggus Dickus 77
Biggus Dickus 77
I am not sure where my error is, be it in the list appending mechanism or in my for loop used to print out the objects. Any help is greatly appreciated.
class Student(object):
fname = ""
lname= ""
idNo = 0
def __init__(self, firstname, lastname, idnumber):
self.fname = firstname
self.lname = lastname
self.idNo = idnumber
def make_student(fname, lname, idNo):
student = Student(fname, lname, idNo)
return student
def main():
maxStudCount = 0
studentList = []
studQuery = raw_input("Would you like to add a student? (Type 'Yes' or 'No'): ")
while studQuery == 'Yes' and maxStudCount < 10:
fname = raw_input("Enter first name: ")
lname = raw_input("Enter last name: ")
idNo = raw_input("Enter ID No: ")
person = make_student(fname, lname, idNo)
studentList.append(person)
maxStudCount = maxStudCount + 1
studQuery = raw_input("Add another student? ('Yes' or 'No'): ")
for item in studentList:
print fname, lname, idNo
if __name__ =='__main__':
main()
You are referencing the local variables fname, lname, and idNo that you last set in the while loop. The variables that you want are stored separately in each instance of the Student class. Try this for loop instead:
for item in studentList:
print item.fname, item.lname, item.idNo

I am trying to create an address book program that will append user input to its appropriate list

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()

Categories

Resources