[Solved] What does this function with a, b = b, a + b do? [closed]


To summarize:

The function prints out the first N numbers in the Fibonacci sequence.

This is a sequence starting with 1, 1 and each following term is the sum of the two previous terms.

a, b = b, a + b

Here, you have 2 variables. a is always the current term and b is the next term. Each iteration, after printing the current term, you assign the next term to a and calculate the term after that.

a: current term
b: the next term
a+b: the term after that

You can read more about swapping variables using this method on this SO post.

From the accepted answer by @eyquem:

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

Documentation: Expressions ยง Evaluation Order

4

solved What does this function with a, b = b, a + b do? [closed]