0

so I'm a beginner programmer and I'm trying to build a python program to print the Fibonacci sequence. my code is as follows:

fib_sequence = [0,1,1]

def fib_add(x):
   fib_seq.insert(x, int(fibseq[x-1]+fibseq[x-2])

for n in range(2,10):
   fib_add(n)
   print(fib_seq)

the program says there is a syntax error at the colon on

for n in range(2,10):

I don't know how to correct it

1
  • Adding the exact error log would help as it does not looks incorrect. Although looks like a closing brace missing near int(fibseq[x-1]+fibseq[x-2]) Commented Mar 22, 2019 at 5:41

4 Answers 4

1

Interestingly, that is not where the syntax error is. It is the preceding line that is the problem:

   fib_seq.insert(x, int(fibseq[x-1]+fibseq[x-2]))

This line was missing closing parentheses. What happens in such cases is that, since the parentheses were not closed, the Python interpreter continues looking for more stuff to put in the expression. It hits the for in the next line and continues all the way to right before the colon. At this point, there is a way to continue the code which is still valid.

Then, it hits the colon. There is no valid Python syntax which allows a colon there, so it stops and raises an error at the first token which is objectively in the wrong place. In terms of your intention, however, we can see that the mistake was actually made earlier.

Also, as noted in a comment, your original list was named fib_sequence, while in the rest of your code you reference fib_list. This will raise a NameError.

Sign up to request clarification or add additional context in comments.

Comments

0

You have to place your for loop code inside main. Also as the other answer suggests, you must add another parenthesis after

fib_seq.insert(x, int(fibseq[x-1]+fibseq[x-2]))

if __name__ == '__main__':
   for n in range(2,10):
   fib_add(n)
   print(fib_seq)

1 Comment

I think there is actually no need to do so, since this code is being run only as a script, presumably.
0

While you have some useful answers, you might look into generators, they make Python a powerful language:

def fibonacci():
    x, y = 0, 1
    while True:
        yield x
        x, y = y, x + y

for x in fibonacci():
    if x >= 10:
        break
    print(x)

This prints

0
1
1
2
3
5
8

Comments

0

Here is the corrected code:

fib_seq = [0,1,1]

def fib_add(x):
   fib_seq.insert(x, int(fib_seq[x-1]+fib_seq[x-2]))

for n in range(3,10):
   fib_add(n)
   print(fib_seq)

Resulting Output:

[0, 1, 1, 2]
[0, 1, 1, 2, 3]
[0, 1, 1, 2, 3, 5]
[0, 1, 1, 2, 3, 5, 8]
[0, 1, 1, 2, 3, 5, 8, 13]
[0, 1, 1, 2, 3, 5, 8, 13, 21]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.