4.2 The while Loop
Example
while loop for Fibonacci Numbers
Fibonacci Numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
The first two terms are 1 and 1. All other terms are obtained by adding the preceding two terms.
Below is a code that lists Fibonacci numbers up to a user given count.
# type in the number of Fibonacci number you want to list and press enter.
# n = input("How many Fibonacci numbers? Type a number and press enter. ")
n = "5" # ← web edition: the value the book's own run typed in
n = int(n) # convert it to an integer
i = 0 # set i to zero initially
a = 1 # first number is 1
b = 1 # second number is 1
while i < n: # i starts at zero and ends at n-1
print (a)
i = i + 1
c = a + b # sum assigned to c
a = b # second assigned to first
b = c # sum assigned to second
Show expected output
How many Fibonacci numbers? Type a number and press enter. 5
1
1
2
3
5Lab 4.2.1
List the first 20 Fibonacci numbers.
Lab 4.2.2
Write a Python code that lists all positive integers starting from 1 till a user given number.
Adapted from Python for Introductory Statistics: Student's Lab Workbook, by Simon Aman (Truman College, City Colleges of Chicago), licensed under CC BY 4.0. Changes were made: reformatted as an accessible XYZ web edition with live in-browser code cells. License: CC-BY-4.0.