In my Python course I have an exercise about Fibonacci numbers. Below you encounter the complete text of chapter 4.1.5.7.
My question is about in the function itself. Particularly I am puzzled what is happening inside the loop:
for i in range(3, n + 1):
sum = elem1 + elem2
elem1, elem2 = elem2, sum
return sum
In the third line you see elem1 comma elem2 is equal to elem2 comma sum. What does it mean?
Can someone please explain step by step how I can interpret the content of this loop?
- Complete text of chapter 4.1.5.7:
Some simple functions: Fibonacci numbers Are you familiar with Fibonacci numbers?
They are a sequence of integer numbers built using a very simple rule:
the first element of the sequence is equal to one (Fib1 = 1) the second is also equal to one (Fib2 = 1) every subsequent number is the sum of the two preceding numbers (Fibi = Fibi-1 + Fibi-2) Here are some of the first Fibonacci numbers:
fib1 = 1
fib2 = 1
fib3 = 1 + 1 = 2
fib4 = 1 + 2 = 3
fib5 = 2 + 3 = 5
fib6 = 3 + 5 = 8
fib7 = 5 + 8 = 13
What do you think about implementing it as a function?
Let's create our fib function and test it. Here it is:
def fib(n):
if n < 1:
return None
if n < 3:
return 1
elem1 = elem2 = 1
sum = 0
for i in range(3, n + 1):
sum = elem1 + elem2
elem1, elem2 = elem2, sum
return sum
for n in range(1, 10): # testing
print(n, "->", fib(n))
Analyze the for loop body carefully, and find out how we move the elem1 and elem2 variables through the subsequent Fibonacci numbers.
The test part of the code produces the following output:
1 -> 1
2 -> 1
3 -> 2
4 -> 3
5 -> 5
6 -> 8
7 -> 13
8 -> 21
9 -> 34
Source available on Cisco Networking Academy - Course name: PCAP - Programming Essentials in Python - module 4, chapter 4.1.5.7 titled "Creating functions | Fibonacci numbers".