Python两种赋值为什么效果不同?
巴扎黑
巴扎黑 2017-04-17 11:45:59
[Python讨论组]
a = 0
b = 1
while b<10:
    print b
    #a,b=b,a+b
    a = b
    b = a + b
巴扎黑
巴扎黑

全部回复(2)
PHP中文网

看你的代码,你是想写个fibonacci数列的程序吧,a,b = b, a + b 没有啥问题就是把a拿到b的值,b拿到a+b的值,第二段a = b, 你把b赋值给了a,导致这个时候a和b都是b的值,你再调用b=a+b就等于把b变成双倍的b,正确的写法,你应该把a存在一个temp中

temp = a
a = b
b = temp + b

阿神

我来补充点文档。你是从这里看到这段代码的吗?下边有解释,注意我加粗的地方:

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.

你拆开之后求值顺序就变了。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号