4

Hi I'm trying to create a Fibonacci sequence generator in Python. This is my code:

d =raw_input("How many numbers would you like to display")

a = 1
b = 1

print a
print b

for d in range(d):
    c = a + b 
    print c
    a = b
    b = c

When I ran this program, I get the error:

File "Fibonacci Sequence Gen.py", line 10, in <module>
    for d in range(d):
TypeError: range() integer end argument expected, got str

Thanks for your help, I'm trying to teach myself python with basic projects.

1

6 Answers 6

7

raw_input returns a string. So convert d to an integer with:

d = int(d)

One more thing: Do not use for d in range(d). It works but it is awful, unpythonic, whatever.
Try this way for example:

numbers = raw_input("How many numbers would you like to display")

a = 1
b = 1

print a
print b

for d in range(int(numbers)):
    c = a + b 
    print c
    a = b
    b = c

Edit: I complete below the answer with additional code tuning (thanks to commenters):

# one space will separate better visually question and entry in console
numbers = raw_input("How many numbers would you like to display > ")    

# I personnally prefer this here, although you could put it
# as above as `range(int(numbers))` or in `int(raw_input())`
# In a robust program you should use try/except to catch wrong entries
# Note the number you enter should be > 2: you print 0,1 by default
numbers = int(numbers)  

a, b = 0, 1        # tuple assignation
                   # note fibonnaci is 0,1,1,2,3...

print a            # you can write this as print "%i\n%i" % (a, b)
print b            # but I think several prints look better in this particular case.

for d in range(numbers - 2):  # you already printed 2 numbers, now print 2 less
    c = a + b 
    print c
    a, b = b, c    # value swapping.
                   # A sorter alternative for this three lines would be:
                   # `a, b = b, a + b`
                   # `print b` 
Sign up to request clarification or add additional context in comments.

11 Comments

+1 Nice and simple... and you beat me to the punch reformatting the question by a couple seconds ;)
More pythonic would be in-place value swapping, I believe: a, b = b, c.
Or alternatively, you could eliminate c completely: a,b = b, a+b; print b
@ChadMiller: Ok, but of course ; should be replaced by line break :)
@Tadeck the ; syntax that ChadMiller used is perfectly valid python. It is just not typical or desirable most of the time. In the context of code in a comment, it is both more desirable and less surprising than adding \n's ;)
|
4

Problem

The problem here is that here:

d = raw_input("How many numbers would you like to display")

you assign string from the input into the d variable, and later you pass it to range(). But range() expects expects integers, not strings, and Python does not convert it automatically (it leaves conversion to you).

Solution

The solution is to convert result of raw_input() into int like that:

d = int(raw_input("How many numbers would you like to display"))

and everything will work unless you provide non-integer.

But there is better (shorter, more efficient, more encapsulated) method of generating Fibonacci numbers (see below).

Better method of generating Fibonacci numbers

I believe this is the best (or nearly the best) solution:

def fibo(n):
    a, b = 0, 1
    for i in xrange(n):
        yield a
        a, b = b, a + b

This is a generator, not a simple function. It is very efficient, its code is short and does not print anything, but you can print its result like that:

>>> for i in fibo(20):
    print i,


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

or convert it into a list like that:

>>> list(fibo(20))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]

Applying the above in your case

After applying the above to your code, it could look like this:

def fibo(n):
    a, b = 0, 1
    for i in xrange(n):
        yield a
        a, b = b, a + b

d = int(raw_input("How many numbers would you like to display"))
for i in fibo(d):
    print i

Does it answer your question?

3 Comments

Your function prints n+1 numbers instead of n. For the most general solution you could remove xrange() from fibo() function and use itertools.islice(), example
@J.F.Sebastian: You were right about n+1 - I misunderstood the task (and returned all the numbers until the one for n instead of the first n numbers). I am not sure however, how this solution may be more general, could you explain? Also what do you think about this: ideone.com/DOSE9?
More general means it is applicable in a wider context e.g., fib() from my example may be used to generate all fibonacci numbers less than a 100000 without changing fib() function itself. The more general the solution at the more global scope it could be defined therefore it doesn't make sense to put a fib() inside fibo().
3

You have to convert the input to a number, like this:

d = int(raw_input("How many numbers would you like to display: "))

Also, just for fun, the fibonacci sequence can be expressed more succinctly:

a, b = 0, 1
for i in range(d):
    print a
    a, b = b, a+b

Comments

2

raw_input returns string type.You need to convert it to int.

>>> x = raw_input()
2
>>> x
'2'
>>> type(x)
<type 'str'>

and range function requires int as an argument not string.

Thats why when i do

>>> range(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got str.

So, change it to

for x in range(int(d)):

Comments

1

Simpler method:

a = [0,1]
for n in range(1,41):
  a.append(a[n]+a[n-1])
  print a[-1]

1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141

Comments

0

I see many over complicated Fibonacci Sequence programs so I just did this with a while loop; changing the number after the while loop

a = 0 b = 1 while a <= 1000000000: #Changing this number will change how long the sequence goes on for print(a) print(b) a = a+b b = b+a I know this isn't your program but it is a very basic version; I hope this helps :)

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.