python 多变量赋值

为什么我用start,stop=10
这样写就不行,必须在后面再加上一个start!

回答

至于为什么需要这样赋值,可能跟楼主学习过C,C++或者JAVA语言有关,举例来讲, 在C语言中,如下代码是可以正常编译的:
#include <stdio.h>int main()
{
 int start, stop  = 10;
 int a;
 printf("start:%d, stop:%d, a:%d", start, stop, a);
 return 0;
}
输出:start:0, stop:10, a:0
说明10赋值给了stop, start跟a一样,你只是定义了这两个变量,然后C编译器自动把他们初始化为0

在python就不太一样, python无需变量申明,你只要使用变量并同时赋值,这个变量就产生了,所以像上述语句中start,a变量都只是定义,在python中是不允许的。
另外python中有多变量赋值这个概念
如:
>>> v = ('a', 'b', 'e')
>>> (x, y, z) = v     
>>> x 'a'
>>> y 'b'
>>> z 'e'
所以如果像以下方式赋值的话:start,stop=10
10只是赋值给了start,而stop没有被赋值,所以出错。
可以这样 start,stop = 10 , 20   
输出: start=10, stop=20
如果
 start = 9
 start,stop = 10 , start 输出:start = 10stop = 9

参考:

http://zhidao.baidu.com/question/230686818.html?         from=pubpage&msgtype=2http://zhidao.baidu.com/question/130438908.html


转载自: http://my.oschina.net/liango/blog/79789

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章