Reputation: 1
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
Upvotes: 0
Views: 57
Reputation: 266
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]
Upvotes: 0
Reputation: 43199
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
Upvotes: 0
Reputation: 204
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)
Upvotes: 0
Reputation: 19895
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
.
Upvotes: 1