October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Fibonacci Series in Python: For Loop, While Loop and Recursion

Generate Fibonacci numbers in Python with a for loop, while loop, or recursion. See when to use each method and how to return the sequence as a list.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a for loop when you want a fixed number of Fibonacci terms, a while loop when you want terms below a value limit, and recursion to express the mathematical definition. Each version below uses the convention fib(0) = 0, fib(1) = 1, producing 0, 1, 1, 2, 3, 5, 8.

How the Fibonacci sequence is generated

Every term after the first two is the sum of the two before it. Starting with 0 and 1, the next term is 0 + 1 = 1, then 1 + 1 = 2, then 1 + 2 = 3.

In the loop examples, a and b hold two consecutive values. After using the current value, update both variables together:

a, b = b, a + b

Python evaluates the right-hand side before assigning either variable, so the old b becomes the new a, and the sum of the old pair becomes the new b. This is the pattern in the Python 3.11 tutorial’s Fibonacci example.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Generate a fixed number of terms with a for loop

Use a for loop when the number of terms is known in advance. range(n) provides exactly n iterations, so the loop prints exactly that many values.

def fibonacci_terms(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=" ")
        a, b = b, a + b

fibonacci_terms(7)

Output:

0 1 1 2 3 5 8

The underscore in for _ in range(n) signals that the loop needs to repeat a fixed number of times but does not use the iteration number. Python’s control-flow tutorial describes for as iterating over the items of a sequence; here, range(n) supplies the count.

Generate values below a limit with a while loop

Use a while loop when the stopping rule is a condition on the current value, not a term count. This example prints each Fibonacci value while it is less than limit:

def fibonacci_below(limit):
    a, b = 0, 1
    while a < limit:
        print(a)
        a, b = b, a + b

fibonacci_below(10)

Output:

0
1
1
2
3
5
8

The Python tutorial explains that a while loop executes as long as its condition remains true; its Fibonacci example uses a < 10. When the current value reaches or exceeds the limit, the loop stops. The final update may calculate that next value even though it is not printed, because the condition is checked before the next iteration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A value limit and a term count are different requests. For example, “print seven terms” is a count-based task for range(7); “print values below 10” is a boundary-based task for while a < 10.

Calculate one indexed value with recursion

Recursion defines a Fibonacci value in terms of smaller Fibonacci values. The base cases stop the calls; without them, the function would keep calling itself.

def fib(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fib(n - 1) + fib(n - 2)

print(fib(6))  # 8

This follows the recurrence fib(n) = fib(n - 1) + fib(n - 2) for n greater than 1. The base cases establish fib(0) = 0 and fib(1) = 1, matching the sequence convention used above. OpenStax presents this recurrence in its lesson on mathematical recursion in Python.

To display a series with this single-value function, call it for successive indices:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
for n in range(7):
    print(fib(n), end=" ")

This combines recursion for each value with a loop to choose the indices. It returns or prints the same sequence, but it is not the same implementation as a loop that carries the current pair forward.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Return values when another part of your program needs the sequence

The examples above print values for display. Printing sends text to output; returning makes data available to the caller. For reusable results, build and return a list:

def fibonacci_list(n):
    values = []
    a, b = 0, 1
    for _ in range(n):
        values.append(a)
        a, b = b, a + b
    return values

terms = fibonacci_list(7)
print(terms)

Output:

[0, 1, 1, 2, 3, 5, 8]

The Python control-flow tutorial contrasts a print-oriented fib example with fib2, which builds and returns a list. Returning values lets the caller inspect, transform, or reuse the sequence instead of only displaying it.

Which Fibonacci method should you use?

Method Stopping rule Best fit What it demonstrates
for loop A fixed iteration count such as range(n) You know how many terms to produce Repeating a fixed number of times while updating a pair
while loop A condition such as a < limit You want terms below a value boundary Continuing until a condition becomes false
Recursion Base cases for n == 0 and n == 1 You are learning recurrence and function calls Defining a value using smaller instances of the same problem

The loop versions provide direct ways to generate a sequence by carrying forward two values. The recursive version makes the mathematical definition visible. The cited Python and OpenStax materials establish these patterns, but do not provide a benchmark comparing their speeds or a practical input cutoff; choose based on the stopping rule and the concept you want to express.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.