Reputation: 134
I ran into a problem when trying to solve a problem I saw on stackoverflow. link
Here's my code:
def fizz_buzz(n):
return ['fizzbuzz' if (f:=i%2==0) and (b:=i%5==0) else 'fizz' if f else 'buzz' if b else i for i in range(n)]
print(fizz_buzz(70))
The above code works perfectly but when I try to add a start value to the range()
function I get an error the free variable 'b' referenced before assignment.
I don't understand why this is happening
Upvotes: 0
Views: 55
Reputation: 1847
User user2357112 is right.
Your condition:
(f:=i%2==0) and (b:=i%5==0)
only assigns b if
f
isTrue
, but you try to use b anyway.
I want to add some explanation about that.
It is OK when you start from 0
because the f
is True
at first (0%2==0
), so b
is computed for the next iterations in the forloop; But if you start from 1
, it is not.
For example if you try with range(2, n)
, it works fine.
Upvotes: 1
Reputation: 281476
Your condition:
(f:=i%2==0) and (b:=i%5==0)
only assigns b
if f
is true, but you try to use b
anyway.
Upvotes: 2