python - 修复不显示两个值的 python 代码

标签 python debugging

这是我作业的一部分,我之所以发布此内容是因为我对自己做错了什么感到困惑。

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

这是我的代码,但每当我输入“Li”作为姓氏时,只有 Josh 出现,而​​ Abby 没有出现。有人可以帮我解决吗?非常感谢!

另外,如果上面没有显示,这里是它的链接:code

最佳答案

缩进使 if 语句脱离 for 循环

此外,如果您想打印所有匹配项,则需要存储所有匹配项,因此您需要诸如列表之类的东西!

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

关于python - 修复不显示两个值的 python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63930609/

相关文章:

swift - 使用 Swift/lldb 比较 Intel 和 Arm 寄存器

perl - 如何调试突然退出的 Perl 程序?

django - 在 Django 中为请求设置断点的位置(在调度之前)?

python - 在 txt 中查找分隔符以使用 Python 转换为 csv

python - 获取列表 [1,1,2,2,..] 并将其添加到数据框的列中

支持 Black Boxing 的 Python 调试器?

ios - 无法打开持久连接的日志,即在 iPhone 上推送日志

python - 失败时如何重试 urllib2.request?

python - 在 pycrypto 中将公钥导出为二进制文件

python-pptx 库 : Slide Masters of different Powerpoint templates are of different order (index)