创建fibonacci序列生成器(初学者Python)

the*_*o22 4 python

嗨,我正在尝试用Python创建一个Fibonacci序列生成器.这是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

当我运行这个程序时,我收到错误:

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

感谢您的帮助,我正在尝试用基本项目教自己python.

joa*_*uin 7

raw_input返回一个字符串.所以将d转换为整数:

d = int(d)
Run Code Online (Sandbox Code Playgroud)

还有一件事:不要使用for d in range(d).它有效,但它很糟糕,无声,无论如何.
试试这种方式,例如:

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
Run Code Online (Sandbox Code Playgroud)

编辑:我在下面的答案中完成了额外的代码调整(感谢评论者):

# 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` 
Run Code Online (Sandbox Code Playgroud)

  • 或者,您可以完全消除c:a,b = b,a + b; 打印b (3认同)