gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:43:02 24 4
gpt4 key购买 nike

您好,我正在尝试用 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。

最佳答案

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

d = int(d)

还有一点:不要使用for d in range(d)。它有效,但它很糟糕,非 pythonic,等等。
例如尝试这种方式:

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`

关于python - 创建斐波那契数列生成器(初学者 Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8957310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com