Using Iteration and a Python Function
For more information on concepts covered in this lesson, you can check out Python Inner Functions: What Are They Good For?.
00:00 Using Iteration and a Python Function. The example seen previously implements a recursive solution that uses memoization as an optimization strategy. In this section, you’ll code a function that uses iteration. The code seen next on-screen implements an iterative version of your Fibonacci sequence algorithm.
00:25
Line 3 defines fibonacci_of()
, which takes a positive integer, n
, as an argument. Lines 5 to 8 perform the usual validation of n
.
00:45
Lines 11 and 12 handle the base cases where n
is either 0
or 1
. Line 14 defines two local variables, previous
and fib_number
, and initializes them with the first two numbers in the Fibonacci sequence.
01:03
Line 15 starts a for
loop that iterates from 2
to n + 1
. The loop uses an underscore for the loop variable because it’s a throwaway variable and you won’t be using this value in the code.
01:16 Line 18 computes the next Fibonacci number in the sequence and remembers the previous one. And finally, line 20 returns the requested Fibonacci number.
01:30
To give this code a try, make sure you’ve saved it as fibonacci_func.py
, and then open an interactive session in the same directory you saved the file in.
02:06
This implementation of fibonacci_of()
is quite minimal. It uses iterable unpacking to compute the Fibonacci numbers during the loops, which is quite efficient memory-wise. However, every time you call the function with a different value of n
, it needs to recompute the sequence entirely.
02:25 One possible solution for this would be to make use of closures and make the function remember the already-computed values between calls. You can learn more about this in this Real Python course.
02:38 In the next section, we’ll take a look back at what you’ve covered in this course.
Become a Member to join the conversation.