Code Explanation:
Line 1 — Define the Fibonacci function factory
def make_fibonacci():
This defines a function named make_fibonacci that will return another function capable of producing the next Fibonacci number each time it’s called.
Line 2 — Initialize the first two numbers
a, b = 0, 1
Sets the starting values for the Fibonacci sequence:
a = 0 (first number)
b = 1 (second number)
Line 3 — Define the inner generator function
def next_num():
Creates an inner function next_num that will update and return the next number in the sequence each time it’s called.
Line 4 — Allow modification of outer variables
nonlocal a, b
Tells Python that a and b come from the outer function’s scope and can be modified.
Without nonlocal, Python would treat a and b as new local variables inside next_num.
Line 5 — Update to the next Fibonacci numbers
a, b = b, a + b
The new a becomes the old b (the next number in sequence).
The new b becomes the sum of the old a and old b (Fibonacci rule).
Line 6 — Return the current Fibonacci number
return a
Returns the new value of a, which is the next number in the sequence.
Line 7 — Return the generator function
return next_num
Instead of returning a number, make_fibonacci returns the function next_num so it can be called repeatedly to get subsequent numbers.
Line 8 — Create a Fibonacci generator
fib = make_fibonacci()
Calls make_fibonacci() and stores the returned next_num function in fib.
Now, fib() will give the next Fibonacci number each time it’s called.
Line 9 — Generate and print first 7 Fibonacci numbers
print([fib() for _ in range(7)])
[fib() for _ in range(7)] calls fib() seven times, collecting results in a list.
Output:
[1, 1, 2, 3, 5, 8, 13]
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment