Python 赋值

赋值语句是Python基本的语法,给变量赋值,给对象命名,都是赋值语句。

Python与C语言不同之处在于,变量不需要先声明,可以直接赋值使用,但是在引用前必须先赋值。变量名在首次赋值时会被创建。

隐式赋值

Python中,赋值语句不仅仅是‘=’,赋值语句在很多情况下使用,比如模块导入、函数和类的定义、for循环变量以及函数参数都是隐式赋值运算。

基本的赋值语句:

>>> fruit = 'apple' #基本赋值形式
>>> fruit
'apple'
>>> fruit1,fruit2 = 'orange','banana'#元组赋值运算
>>> fruit1,fruit2
('orange', 'banana')
>>> [fruit1,fruit2] = ['apple','grape']#列表赋值
>>> fruit1,fruit2
('apple', 'grape')
>>> fruit1=fruit2='grape'#多目标赋值
>>> fruit1;fruit2
'grape'
'grape'
>>> fruit1 += 'is good'#增强赋值运算
>>> fruit1
'grapeis good'
>>>

使用range赋值

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
《Linux三剑客》视频教程,从零开始快速掌握Linux开发常用的工具:Git、Makefile、vim、autotools、debug,免费赠送C语言视频教程,C语言项目实战:学生成绩管理系统。详情请点击淘宝链接:Linux三剑客