创建斐波那契数列生成器(初学者Python)

4 投票
6 回答
16045 浏览
提问于 2025-04-17 10:48

你好,我正在尝试用Python创建一个斐波那契数列生成器。这是我的代码:

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

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

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

谢谢你的帮助,我正在通过一些基础项目自学Python。

6 个回答

3

你需要把输入的内容转换成数字,像这样:

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

另外,顺便说一下,斐波那契数列可以用更简洁的方式表示:

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

问题

这里的问题是:

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

你把输入的字符串赋值给了 d 这个变量,然后把它传给了 range()。但是 range() 其实是需要整数,而不是字符串,Python 不会自动帮你转换(这个转换得你自己来做)。

解决方案

解决这个问题的方法是把 raw_input() 的结果转换成 int,可以这样做:

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

这样一来,程序就能正常运行,前提是你输入的得是整数。

不过,还有一种更好(更简短、更高效、更封装)的生成斐波那契数的方法(见下文)。

更好的生成斐波那契数的方法

我认为这是最好的(或者说接近最好的)解决方案:

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

这个是一个生成器,不是简单的函数。它非常高效,代码也很简短,并且不会打印任何东西,但你可以这样打印它的结果:

>>> 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

或者你可以这样把它转换成列表:

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

在你的案例中应用上述内容

把上面的内容应用到你的代码中,可能会变成这样:

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

这样能回答你的问题吗?

7

raw_input会返回一个字符串。所以你需要把d转换成一个整数,可以用下面的方式:

d = int(d)

还有一点:不要使用 for d in range(d)。虽然这样可以运行,但效果很差,不符合Python的风格,怎么说都不太好。
你可以试试下面这种写法:

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

补充说明: 我在下面的回答中添加了一些代码优化(感谢评论者的建议):

# 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` 

撰写回答