Wednesday, 13 August 2025

Python Coding challenge - Day 669| What is the output of the following Python Code?

 


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]

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (150) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (216) Data Strucures (13) Deep Learning (67) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (185) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1215) Python Coding Challenge (882) Python Quiz (341) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)