I have some code that creates a variable if a certain condition is met:
if self.left:
left_count = self.left.isUnivalTree()
A few lines down I have the code:
if left_count and right_count:
total_count = right_count + left_count
This throws the following error:
local variable 'left_count' referenced before assignment
How do I get around this? Surely by saying if left_count...
I account for the fact it may not
(This error is fixed by setting a default value to all the parameters in the function but I am just wondering if there is a simpler way around this as I need to set a default value for 5 parameters?)
You aren't assigning if self.left
isn't True
, try the below which will set a default of None
:
left_count = self.left.isUnivalTree() if self.left else None
As per your question update, setting default parameters on the function is better, that's exactly what they are there for.
Instead of:
left_count = False
if self.left: left_count = self.left.isUnivalTree()
Just use the short circuiting behaviour of and
:
left_count = self.left and self.left.isUnivalTree()
If isUnivalTree
returns a bool (which it should because of the name):
left_count = self.left and self.left.isUnivalTree()
Otherwise:
left_count = self.left.isUnivalTree() if self.left else None
or catch the NameError
try:
if left_count and right_count: total_count = right_count + left_count
except NameError:
print('NameError catched')
total_count = 0
or check if it is defined:
if 'left_count' in locals():
print('left_count is defined')
it all depends on what fits best in your work flow
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.