When trying to write a one line Fibonacci sequence that I understand, I'm having an issue with fib = lambda a, b: b, a + b
as "'b' is not defined"
However, when I do sum = a, b, c: a + b + c
I get no errors. sum(1, 2, 3)
runs perfectly and returns 6
.
I've researched global variables and found that if I set a and b to Null before starting, it doesn't give me an error, but is there a way not to do this?
You need to put parentheses around the lambda body:
fib = lambda a, b: (b, a + b)
Otherwise Python thinks it is this:
fib = (lambda a, b: b), a + b
Incidentally, there's no real purpose in using lambda
if you're just going to assign the function to a name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With