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.
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`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With