Fixing python code that doesn't show both values

Viewed 32

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

3 Answers

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