我对编码相当陌生,我一直在使用alexbowers的《Python初学者手册》。每一章的结尾都是一个实验练习,这一章是关于Fabonacci的,这一章本身是关于forLoops,whileLoops,Try Except和Finally,以及中断和继续。 我对解很困惑,尤其是关于变量“set”的那些行,有人能给我解释一下这个解吗,因为他们没有在书中解释它。。。谢谢你
f0 = 0
f1 = 1
set = False
while True:
fn = f0 + f1
f0 = f1
f1 = fn
if (fn > 100):
set = True
else:
set = False
print(fn)
if (set == True):
break
在本例中,
set
一旦数字超过100
,它将停止循环,因此它不会永远运行。这实际上是一个相当糟糕的斐波纳契序列,但我会解释,因为它无论如何都是有效的代码。。。在不管怎样,我会做:
^{pr2}$我假设你知道Fibonacci序列是什么(如果不知道,读this)。我一次就走这一步
这些是用于计算Fibonacci序列的变量。
f0
是序列中的第一个数字,f1
是第二个数字。在
^{pr2}$set
将用作以下循环的条件,以确定何时停止。在这是一个无限的while循环。在
^{3}$计算序列中的下一个数字。在
更新旧变量。在
如果序列中的数字大于100,请将
set
设置为True
。否则将set
设置为False
(它已经是了)。在打印当前序列号。在
如果
^{8}$set
是True
,则离开无限循环。在注意:此代码可以轻松简化。我很惊讶它出现在一本书里。您可以将其简化为:
与使用
set
不同的是,可以用这种方式编写代码,以实现相同的目的,否则将完全相同:使用
set
是使用适当循环条件(即fn <= 100
位)的一种奇怪且冗长的替代方法,并且可能只有在有和没有else
子句的if语句的示例中才会出现这种情况。在使用本书其他地方可能遇到的更高级的逻辑,您还可以消除
^{pr2}$fn
变量:行
^{3}$f0, f1 = f1, f0 + f1
类似于:除了在
f0
或f1
更改值之前,对两个右侧表达式求值。在希望看到它以这种简化的形式写下来,可以帮助你准确地理解到底发生了什么。在
相关问题 更多 >
编程相关推荐