Can someone explain me my previously written code?

def fibo(pattern,n):
    a = pattern
    i = 1
    while n - 1 >= len(a):
        a.append(a[i-1] + a[i])
        i = i + 1
    return a
        
print fibo([0,1],10)

Over here the while condition says that while n-1 is more than or equal to length of a the program will run. But I can’t get my code. Well I want to get an array of length 10. So going by the while statement the programme should give me an array of length of 9. But it gives me length of 10 array.
Please help.
@cpradio

Hi @akul3007, when you post code here, you need to format it so that it will display correctly.

You can highlight your code, then use the </> button in the editor window, which will format it, or you can place three backticks ``` (top left key on US/UK keyboards) on a line before your code, and three on a line after your code. (I find this approach easier, but unfortunately some European and other keyboards don’t have that character.)

1 Like

You are indeed correct about that, but you missed one important fact. The while loop states >= (greater than or equal to), so that means even when n - 1 == 9. if the length of the array is also 9, it will run again, as 9 is equal to 9, thus producing a 10th item in the array.

1 Like

Thanks. Will take care of this from next time onwards

Make sense. So if I make my while condition like this
while n > len(a)

So here I will get an array of length 10 because when the length will be 9 the while condition will be checked as 10 > 9 and the programme will run again for the last time. Because after this the length will become 10 and the while condition will be false i.e. 10 > 10 which is false. Am I right ?

1 Like

Yes, that is correct.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.