Skip to main content
 首页 » 编程设计

python之初学者 Python 用户 bool 查询

2024年12月31日8wuhuacong

CodeAcademy 的 Python 类(class)让我学习循环函数,但我不明白结果。目标是查看一个列表是否是另一个列表的镜像。即 [1,2,3] 到 [3,2,1]

20 分钟后我查看了解决方案,但我不明白为什么每次都不会返回 True?:

def reversed_list(lst1, lst2): 
  for index in range(len(lst1)): 
    if lst1[index] != lst2[len(lst2)-1-index]: 
      return False 
  return True 

“return True”缩进到与“for index”相同的级别,这将覆盖从前一行返回的任何值。

或者,当我在“if”缩进处引入“else”时,一切都返回 True:

def reversed_list(lst1, lst2): 
  for index in range(len(lst1)): 
    if lst1[index] != lst2[len(lst2)-1-index]: 
      return False 
    else: 
      return True 

任何人都可以帮助菜鸟吗?

请您参考如下方法:

return False 导致函数在返回 False 时完全退出,因此在这种情况下永远不会到达 return True 行。提前放置 return 语句是中断函数执行的一种方式