a, b = b, a + b
I picked up this coding style from 'Building Skills in Python'. Coming from PHP and Obj-C this type of multi-variable assignment wasn't available (at least not that I've seen). But it seems more logical to me. Afterall, why should I have to assign 'a' to a 'holding variable' before it is replaced.
Question is, is this coding style pythonic?
Here's a sample Fibonacci program:
a, b = 1, 2
output = str(a)
while b<=100:
output = output + " " + str(b)
a, b = b, a + b
print output
And, what's the best way you found helped you write more pythonic code?
The tuple unpacking is pythonic, but some other parts of your snippet aren't. Here's a slight modification using a generator to avoid (and separate) the string concatenation:
def fib(k=100):
""" Generate fibonacci numbers up to k. """
a, b = 1, 2
while a <= k:
yield a
a, b = b, a + b
print(' '.join(map(str, fib())))
# prints: '1 2 3 5 8 13 21 34 55 89'
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