1、赋值语句:使用赋值号(=)将右边的值(表达式)赋给左边变量。如:
bookname = 'Python'
price = 12
saleprice = str(price) # 这里需要先将整数类型的36转化为字符串类型
print('The price of the book '+bookname+' is $'+saleprice) # 运行结果:The price of the book Python is $12.
赋值号“=”:不是相等的意思,可以理解为将右边的值赋给左边的变量。“=”左边必须是一个可以被赋值的变量,“=”右边可以是一个常量、变量或函数的返回值等。赋值语句运行结束后,“=”左边的变量的值更新为“=”右边的值。
2、序列赋值:可以为多个变量分别赋予不同的值,变量之间用英文逗号隔开。
number1,number2 = 8,3.5
print(number1,number2) # 运行结果:8 3.5
序列赋值可以将字符串中的字符依次赋值给多个变量。如:
spell1,spell2,spell3,spell4 = 'Mark'
print(spell1,spell2,spell3,spell4) # 运行结果:M a r k
print(spell3) # 运行结果:r
Python可以通过序列赋值语句实现两个变量值的交换。
spell1,spell2,spell3,spell4 = 'Mark'
spell1,spell2,spell3,spell4 = spell4,spell3,spell2,spell1 # 这里值发生了互换
print(spell1,spell2,spell3,spell4) # 运行结果:k r a M
print(spell3) # 运行结果:a
3、多目标赋值:将同一个值赋值给多个变量。通常只用于赋予数值或字符串这种不可变类型。
spell1=spell2=spell3=spell4 = 'Mark'
print(spell1,spell2,spell3,spell4) # 运行结果:Mark Mark Mark Mark
print(spell3) # 运行结果:Mark
4、复合赋值:是运算操作与赋值操作的组合。
所有复合赋值运算符的优先级和赋值运算符的一样。
+=(加等于),-=(减等于),*=(乘等于),/=(除等于),%=(取余等于),**=(幂等于)
这里以+=(加等于)举例:
names = ['张三','李四','王五','赵六']
wages = [8500,8800,8300,9200]
i = 0
while i < len(names):
name = names[i]
wage = wages[i]
print(name, ':', wage)
i += 1 # 这里意思是将i+1的值再赋值给变量i
"""
运行结果:
张三 : 8500
李四 : 8800
王五 : 8300
赵六 : 9200
"""
print(names[0]+':'+str(wages[0])) # 运行结果:张三:8500
len()函数计算列表长度,这里是4个元素,所以变量i初始值是0,然后是1,依次+1,直到4。