For more information on concepts covered in this lesson, you can check out Python Inner Functions: What Are They Good For?.
Using Iteration and a Python Function
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.
Line 3 defines
fibonacci_of(), which takes a positive integer,
n, as an argument. Lines 5 to 8 perform the usual validation of
Lines 11 and 12 handle the base cases where
n is either
1. Line 14 defines two local variables,
fib_number, and initializes them with the first two numbers in the Fibonacci sequence.
Line 15 starts a
for loop that iterates from
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.
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.
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.