Your function will compute the fibonacci sequence but it's not iterative, it's recursive (the function fib calls itself). If you want to write an iterative function, you must work with a pair of numbers x(n), y(n) = fib(n), fib(n-1). Now you should be able to write a formula which gives the pair x(n), y(n) if you know x(n-1), y(n-1). Also note that you know x(1), y(1).
Just a note that I edited my post above. Your code is good (as a recursive function). I was relying on your initial definition of Fibonacci sequence, which is incorrect, instead of thinking for myself. I removed part of my comment so I don't confuse someone else looking at this.
a generator that produces the elements of the fibonacci series
a = 1
b = 1 while True:
a, b = a + b, a
def nth(series, n):
returns the nth element of a series, consuming the earlier elements of the series
for x in series:
n = n - 1
if n <= 0: return x
print nth(fib(), 10)
It seems that all you have done is to copy code you found somewhere else. For example, what does this line that you posted mean and why would it be used in a fib sequence?
a, b = b, a + b
Start with a routine to get the number(s) to begin with and the number of fibs that you want, or the maximum value you don't want to exceed before stopping. Post the code here. Then write some code to calculate one fib number in a sequence, given the previous sequence. Because a fib can start with any number(s), you first have to set the parameters and then calculate the fibs.
As you probably already know, and have been told earlier in this thread, iterative means you have to solve the problem in one function without calling the same function from within the same function (recursion)
What I would use for this is lists.
Define a list with the initial solutions, i.e for n = 0 and n = 1. Then do a loop and calculate every solution from 2 to and including n.
To start you off:
solutions = [1, 1] # Create the list containing the initial solutions
# Test if you already know the solution for n, if so - return the solution
for x in range(2, n + 1): # iterate over every value from fib(2) to fib(n) and generate the solutions
# here you calculate the solution for fib(x) by appending (x - 1) + (x - 2) from solutions to the list
Post your function back and let's see what you got :)