简体   繁体   中英

While-loop Python Fibonacci

I am new to python and I have really poor expiriences with other codes. For the most of you a stupid question but somewhere I should start.

 def fib(n):
 a, b = 0, 1
 while a < n:
     print(a, end=' ')
     a, b = b, a+b
 print()

I don't understand why one should enter a, b = b, a+b I see and understand the result and I can conclude the basic algorithm but I don't get the real understanding of what is happening with this line and why we need it.

Many thanks

This line is executed in the following order:

  1. New tuple is created with first element equal to b and second to a + b
  2. The tuple is unpacked and first element is stored in a and the second one in b

The tricky part is that the right part is executed first and you do not need to use temporary variables.

The reason you need it is because, if you update a with a new value, you won't be able to calculate the new value of b . You could always use temporary variables to keep the old value while you calculate the new values, but this is a very neat way of avoiding that.

It's called sequence unpacking.

In your statement:

a, b = b, a + b

the right side b, a + b creates a tuple :

>>> 8, 5 + 8
(8, 13)

You then assign this to the left side, which is also a tuple a, b .

>>> a, b = 8, 13
>>> a
8
>>> b
13

See the last paragraph the documentation on Tuples and Sequences :

The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:

>>> x, y, z = t

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires the list of variables on the left to have the same number of elements as the length of the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM