python之数据类型 & 参数传递
在python中也有着可变类型(mutable)
与不可变类型(immutable)
.不可变类型在定义之后是不能修改的,可变类型是可以作出修改的。
总体分为5大类型。
number类型(int float complex boolean)属于不可变类型
string类型(str)属于不可变类型
list类型属于可变类型
dictionary类型属于可变类型
tuple类型属于不可变类型
1 number类型
如何声明一个number类型的变量?
a=1
a=1.1
a=False|True
a=complex(1,2)
2 string类型
如何声明一个str类型?
s='one'
s="one"
s='''one'''
3 list类型
如何声明一个list类型?
list = [1,2,3,4,5]
4 dictionary类型
如何声明一个dictionary类型?
dic = {'name':'SuperMan','age':21,2:'b'}
5 tuple类型
tuple1 = (1,2,3,4)
6 参数传递
6.1 不可变类型值传递
对于不可变数据类型
的变量在传递的过程中,属于值传递
,在对该变量作操作时,只是对该变量的副本的值进行操作,原先的变量不会改变。
# 值传递
def changeInt(a):
"传入number类型int类型的变量"
a = 10
print(a)
return
b = 1
changeInt(b)
print(b) # 1 说明改动的只是b的副本
6.1 可变类型引用传递
对于可变数据类型
的变量在传递的过程中,属于引用传递
,在对该变量作操作时,是直接对该变量引用指向内存地址的数据进行 操作,原先变量会发生改变
。
# 引用传递
def changeList(mylist):
"对列表中的元素进行修改"
mylist.append([1, 2, 3])
print('mylist = ', mylist)
return
list = [20, 40]
changeList(list)
print(list) # [20, 40, [1, 2, 3]] 说明list是可变的对象,传递时传递的是mylist的内存地址引用
6.3 参数类型
# 1 必备参数
def printme(string):
'必备参数'
print(string)
return
print("hello world") # 必备参数
# print(string="hello me") # 关键字参数
# 2 不定长参数
def printVars(arg1, *other):
print("input string:")
print(arg1)
for i in other:
print(i)
print(printVars(1, 2, 3, 4, 5, 6))
# 3 匿名函数
# 在python中也有匿名函数,可以使用变量接收
# 类比scala中的匿名函数,(a:Int) => print(a),
# python中的匿名函数可以表示为 lambda a,b:a+b
sum1 = lambda a, b: a + b
print(sum1(1, 2)) # 3