0

I have a simple problem and the statement goes like this:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... I want to create the numbers as above:

The code that I am trying to write is as follows:

num(1)=1
num(2)=2
for i in range(3,10):
    num(i)=num(i-1)+num(i-2)
    print num(i)

The algorithm that I designed is as follows:

x(i)=x(i-1)+x(i-2)

I will start from x(3) with x(1) and x(2) unknown. Can anyone help me with in array syntax error ? Thanks.

3 Answers 3

3

You can do:

num = range(1, 10)
num[0] = 1
num[1] = 2
for i in range(2,9):
    num[i]=num[i-1]+num[i-2]
    print num[i]

You need to use [] instead of ()

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

Comments

2

Python uses [] to address indexes in array list, so just use num[i] instead of num(i).

Comments

0

The syntax for lists is to use square brackets ("[" and "]" like "num[3]"), not parenthesis. Then you have to remember that in programming indexes in lists start with 0, not 1. Then when you're done with that you have to create a list in the first place: num = [].

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.