我有一些代码,在满足某个条件时创建一个变量:
if self.left:
left_count = self.left.isUnivalTree()
下面几行我有代码:
if left_count and right_count:
total_count = right_count + left_count
这将引发以下错误:
local variable 'left_count' referenced before assignment
我该怎么办?当然,通过说if left_count...
我可以解释这个事实
(这个错误是通过为函数中的所有参数设置一个默认值来修复的,但是我只是想知道是否有更简单的方法来解决这个问题,因为我需要为5个参数设置一个默认值?)
如果
self.left
不是True
,则不进行赋值,请尝试以下设置None
默认值的方法:根据您的问题更新,在函数上设置默认参数更好,这正是它们的用途
如果
isUnivalTree
返回bool(由于名称的原因,应该返回bool):否则:
而不是:
只需使用
and
的短路行为:相关问题 更多 >
编程相关推荐