理解困难3.2。编程的第一步

2024-04-25 01:27:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始看一本新指南,选择了[python.org网站教程](https://docs.python.org/2/tutorial/。但是,在section 3.2中,我无法理解此代码如何:

a, b = 0, 1
while b < 10:
    print b
    a, b = b, a+b

给我输出

1
1
2
3
5
8

指南提到:

  • The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

有人能帮我简化一下吗?你知道吗


Tags: andtheorgright网站line指南教程
2条回答

第一行可以这样展开:

a = 0
b = 1

不幸的是,最后一行并不是那么容易,因为值是同时“解包”的。在这种情况下,如果要按顺序写入,则需要一个临时变量:

old_a = a
a = b
b = old_a + b

demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place

意味着它首先实现第二个表达式(a+b),然后用未修改的b均衡a,用a+b均衡b。你知道吗

可能是这样的

step1 => a + b
step2 => a = b
         b = step1


            step2       step1     b
loop    |            |        |  
        |            |        | 
        |  a     b   |   mod  |  output
1       |  0     1   |    -   |   >> 1
2       |  1     1   |   0+1  |   >> 1
3       |  1     2   |   1+1  |   >> 2      
4       |  2     3   |   1+2  |   >> 3
5       |  3     5   |   2+3  |   >> 5
6       |  5     8   |   3+5  |   >> 8

相关问题 更多 >