1. Collection
1.1 Characteristics of collections
Sets are unordered, and the elements in the set are unique. Sets are generally used to deduplicate elements in tuples or lists.
1.2 Format of the collection
Format
变量名=set()
变量名.add(元素)
# 必须不能初始化值
or
变量名={元素,元素,,,}
Note: The following writing method is an empty dictionary. If it is empty, it defaults to a dictionary. If there is data, it is judged whether it is a dictionary or a set according to the format.
name={}
1.3 Add elements
1.3.1 add
- the case
nums = {11,24,45,96,28}
nums.add(42)
print(nums)
#{96, 42, 11, 45, 24, 28}
1.3.2 update
- the case
nums = {11,24,45,96,28}
nums2=["anfly","tom"]
nums.update(nums2)
print(nums)
#{96, 'anfly', 11, 45, 24, 28, 'tom'}
1.4: Delete elements
remove,pop,discard
1.4.1 remove
使用remove删除集合中的元素 如果有直接删除 如果没有程序报错
- Case: The element exists
nums = {11,24,45,96,28}
nums.remove(24)
print(nums)
#{96, 11, 45, 28}
- Case: The element does not exist
nums = {11,24,45,96,28}
nums.remove(245)
print(nums)
#KeyError: 245
1.4.2 pop
1、如果集合的元素都是数字, 删除时, 删掉的是最小的数字, 其余数字升序排列
2、如果集合的元素是非数字, 删除时, 删掉的是随机的元素, 其余元素随机排列
3、如果集合里既有数字又有非数字元素, 删除时:
若删掉的是数字, 则一定是删掉了最小的, 其他数字升序排列, 非数字元素随机排列;
若删掉的非数字, 则一定是随机删掉了一个, 其他数字升序排列, 非数字则随机排列.
如果集合没有元素程序报错
- Case: with elements
nums = {11,24,45,96,28}
nums.pop()
print(nums)
#{11, 45, 24, 28}
- Case: no element
nums = {}
nums.pop()
print(nums)
#TypeError: pop expected at least 1 arguments, got 0
1.4.3 discard
使用discard删除 如果元素存在直接删除 如果元素不存在不做任何操作
- Case: The element exists
nums = {11,24,45,96,28}
nums.discard(24)
print(nums)
#{96, 11, 45, 28}
- Case: The element does not exist
nums = {11,24,45,96,28}
nums.discard(242)
print(nums)
#{96, 11, 45, 24, 28}
1.5: Intersection and union of sets
1.5.1: Intersection
使用&连接多个集合,得到相同的元素
- Case: Same elements exist
set1 = {"anfly","tom","haha"}
set2 = {"anfly","susala"}
set3= set1 & set2
print(set3)
Return value:{'anfly'}
- Case: Same elements exist
set1 = {"anfly","tom","haha"}
set2 = {"anfly2","susala"}
set3= set1 & set2
print(set3)
Return value: set()
1.5.2: Union
使用|连接多个集合,得到全部集合中全部的元素
- Case:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
new_set = set1 | set2
print(new_set)
#{1, 2, 3, 4, 5, 6}
2. Function
2.1 What is a function
在开发程序时,需要某块代码多次,但是为了提高编写的效率以及代码的重用,所以把具有独立功能的代码块组织为一个小模块,这就是函数
2.2 Function definition and calling
Format
def 函数名():
执行语句
函数名() #调用函数
- the case
def hello():
print("hello word")
hello()
Notice:
定义了函数之后,就相当于有了一个具有某些功能的代码,想要让这些代码能够执行,需要调用它
调用函数很简单的,通过 函数名() 即可完成调用
每次调用函数时,函数都会从头开始执行,当这个函数中的代码执行完毕后,意味着调用结束了
当然了如果函数中执行到了return也会结束函数
2.3 Function parameters
思考:现在需要定义一个函数,这个函数能够完成2个数的加法运算,并且把结果打印出来,该怎样设计?
- the case
def add2num():
a = 11
b = 22
c = a+b
print c
Thinking: If you want to make a function more general, that is, if you want it to calculate the sum of which two numbers, let it calculate the sum of which two numbers, can you let the function receive data when defining the function? Introduction: parameter
passing
2.3.1: Positional parameters
Format
def 函数名(参数1,参数2):
代码块
函数名(值1,值2)
- Case:
def fun(a,b):
print("a:",a)
print("b:",b)
fun(2,3)
Result: a: 2 b:3
小总结
定义时小括号中的参数,用来接收参数用的,称为 “形参”
调用时小括号中的参数,用来传递给函数用的,称为 “实参”
2.3.2 Keyword parameters
Format
def 函数名(参数1,参数2):
代码块
函数名(参数1=值1,参数2=值2)
Case:
def fun(a,b):
print("a:",a)
print("b:",b)
fun(a=2,b=3)
Result: a: 2 b: 3
Note: When calling parameters , the order of passing parameters can be changed. If there are positional parameters, the positional parameters need to be placed in front of the keyword parameters
. Case:
def fun(a,b):
print("a:",a)
print("b:",b)
fun(3,b=2)
Result: a: 3 b:2
如果关键字参数传参要在位置参数之前,将会报错
Case:Error
def fun(a,b):
print("a:",a)
print("b:",b)
fun(a = 3,2)
#SyntaxError: positional argument follows keyword argument
2.3.3:Default parameters
在形参中默认有值的参数,称之为缺省参数
Case: When calling a function, the value of the default parameter is not passed in
def printinfo(name,age=20):
print("name:",name)
print("age:",age)
printinfo(name="anfly")
#name: anfly
#age: 20
Case: When calling a function, the value of the default parameter is passed in
def printinfo(name,age=20):
print("name:",name)
print("age:",age)
printinfo(name="anfly",age=10)
#name: anfly
#age: 10
the case
def printinfo(age=20,name):
print("name:",name)
print("age:",age)
printinfo(name="anfly",age=10)
#SyntaxError: non-default argument follows default argument
Summarize
调用函数时,缺省参数的值如果没有传入,则取默认值(形式参数),如果传入,则取实际参数
缺省参数一定要位于位置参数的最后面
2.3.4 Indefinite length parameters
有时可能需要一个函数能处理比当初声明时更多的参数, 这些参数叫做不定长参数,声明时不会命名。
Format
def printinfo(*args,**kwargs):
print("args:",args)
print("kwargs:",kwargs)
printinfo(参数)
注意:加了星号(*)的变量args会存放所有未命名的变量参数,args为元组
而加**的变量kwargs会存放命名参数,即形如key=value的参数, kwargs为字典
Case: variable length parameters * args
def printinfo(*args):
print("args:",args)
printinfo(100,200,300,400)
#args: (100, 200, 300, 400)
Case: * args cannot receive parameters of key=value type
def printinfo(*args):
print("args:",args)
printinfo(100,200,300,b = 400)
#TypeError: printinfo() got an unexpected keyword argument 'b'
Case: variable length parameters * * kwargs
def printinfo(**kwargs):
print("kwargs:",kwargs)
printinfo(a=100,b=200,c=300,d= 400)
#kwargs: {'a': 100, 'b': 200, 'c': 300, 'd': 400}
Case: * * kwargs cannot receive unnamed variable arguments
def printinfo(**kwargs):
print("kwargs:",kwargs)
printinfo(100,b=200,c=300,d= 400)
#TypeError: printinfo() takes 0 positional arguments but 1 was given
2.3.5: Parameter position order
Format
def fun(位置参数,*args,缺省参数,**kwargs):
代码块
fun(参数值)
the case
def sun(a,*args,b=22,**kwargs):
print("a:",a)
print("args:",args)
print("b:",b)
print("kwargs:",kwargs)
sun(100,200,300,b=2,m=3,n=4)
return value:
a: 100
args: (200, 300)
b: 2
kwargs: {'m': 3, 'n': 4}
注意:•如果很多个值都是不定长参数,那么这种情况下,可以将缺省参数放到 *args的后面, 但如果有**kwargs的话,**kwargs必须是最后的
2.4: Function return value
Scenario:•I gave my son 10 yuan and asked him to buy me a pack of cigarettes. In this example, 10 yuan is given to my son, which is equivalent to passing the parameters when calling the function. The ultimate goal of letting my son buy cigarettes is to let him bring the cigarettes back to you and then give them to you, right? At this time, the smoke is the return value
format
def sum():
代码块
return 值
sum()
code
def sum(a,b):
return a+b
sum(1,2)
Code: view return value
def sum(a,b):
return a+b
result = sum(1,2) #保存函数的返回值
print(result)
2.4.1: Multiple returns
def create_nums(num):
print("---1---")
if num == 100:
print("---2---")
return num+1 # 函数中下面的代码不会被执行,因为return除了能够将数据返回之外,还有一个隐藏的功能:结束函数
print("return执行之后不会继续执行")
print(“1231223")
else:
print("---3---")
return num+2
print("---4---")
result1 = create_nums(100)
print(result1) # 打印101
result2 = create_nums(200)
print(result2) # 打印202
注意:一个函数中可以有多个return语句,但是只要有一个return语句被执行到,那么这个函数就会结束了,因此后面的return没有什么用处
2.4.2: Return multiple data
code
def divid(a, b):
shang = a//b #取模
yushu = a%b #取余
return shang, yushu #默认是元组
result = divid(5, 2)
print(result)
# 输出(2, 1)
总结:return后面可以是元组,列表、字典等,只要是能够存储多个数据的类型,就可以一次性返回多个数据
2.5: Function type
Classification:
1. 无参数,无返回值
2. 无参数,有返回值
3. 有参数,无返回值
4. 有参数,有返回值
2.5.1: Function with no parameters and no return value
此类函数,不能接收参数,也没有返回值,一般情况下,打印提示灯类似的功能,使用这类的函数
def printMenu():
print('--------------------------')
print(' xx涮涮锅 点菜系统')
print('')
print(' 1. 羊肉涮涮锅')
print(' 2. 牛肉涮涮锅')
print(' 3. 猪肉涮涮锅')
print('--------------------------')
2.5.2: Function with no parameters and return value
•此类函数,不能接收参数,但是可以返回某个数据,一般情况下,像采集数据,用此类函数
def getTemperature():
# 这里是获取温度的一些处理过程
# 为了简单起见,先模拟返回一个数据
return 24
2.5.3: Functions with parameters and no return value
•此类函数,能接收参数,但不可以返回数据,一般情况下,对某些变量设置数据而不需结果时,用此类函数
2.5.4: Functions with parameters and return values
•此类函数,不仅能接收参数,还可以返回某个数据,一般情况下,像数据处理并需要结果的应用,用此类函数
# 计算1~num的累积和(案例需实际演示)
def calculateNum(num):
result = 0
i = 1
while i<=num:
result = result + i
i+=1
return result
2.6: Nesting of functions
一个函数里面又调用了另外一个函数,这就是所谓的函数嵌套调用
the case
def testb():
print("testb start")
print("testb testb 执行")
print("testb end")
def testa():
print("testa start")
testb()
print("testa end")
return value
testa start
testb start
testb testb 执行
testb end
testa end
注意:如果函数A中,调用了另外一个函数B,那么先把函数B中的任务都执行完毕之后才会回到上次 函数A执行的位置
Classwork
写一个函数求三个数的和,并返回结果
写一个函数求三个数的平均值,并返回结果
再写一个函数求每个数与平均值之间的差,并返回结果
写一个函数打印一条横线
打印自定义行数的横线
# 打印一条横线
def printOneLine():
print("-"*30)
# 打印多条横线
def printNumLine(num):
i=0
# 因为printOneLine函数已经完成了打印横线的功能,
# 只需要多次调用此函数即可
while i<num:
printOneLine()
i+=1
printNumLine(3)
2.8: Anonymous functions
lambda函数也叫匿名函数,即函数没有具体的名称
code
g = lambda x :x+1
print(g(1))
def g(x):
return x + 1
print(g(1))
注意:lambda函数可以赋值给变量,默认是返回的,所以不用再加return关键字
注释:例如g = lambda x:x+1,可以看成如下函数,冒号前是参数,可以有多个,用逗号隔开,冒号右边的返回值
3. Variables
3.1: Local variables
definition
局部变量,就是在函数内部定义的变量
constraint
其作用范围是这个函数内部,即只能在这个函数中使用,在函数的外部是不能使用的
code
def test1():
a = 120
print("我是局部变量a:",a)
a = 240
print("修改之后的局部变量a:",a)
def test2():
a =360
print("我是test02函数中的局部变量a",a)
test1()
test2()
return value
我是局部变量a: 120
修改之后的局部变量a: 240
我是test02函数中的局部变量a 360
注意:局部变量的作用,为了临时保存数据需要在函数中定义变量来进行存储
当函数调用时,局部变量被创建,当函数调用完成后这个变量就不能够使用了
3.2: Global variables
definition
在函数外边定义的变量叫做全局变量
constraint
全局变量能够在所有的函数中进行访问
code
a = 100
def test1():
print(a) # 虽然没有定义变量a但是依然可以获取其数据
def test2():
print(a) # 虽然没有定义变量a但是依然可以获取其数据
# 调用函数
test1()
test2()
Return value: 100 100
3.2.1 Global variables and local variables have the same name
code
a = 100 #全局变量
def test1():
a= 300
print("修改后的a:",a)
def test2():
print(a)
# 调用函数
test1()
test2()
Return value: modified a:300 100
注意:函数中的变量修改不会导致全局变量改变
3.2.2: Modification of global variables
Code: the use of global
a = 100 #全局变量
def test1():
global a #将a变成全局变量
a= 300
print("修改后的a",a)
def test2():
print(a)
# 调用函数
test1()
test2()
注意:在函数中出现global 全局变量的名字 那么这个函数中即使出现和全局变量名相同的变量名 = 数据 也理解为对全局变量进行修改,而不是定义局部变量
Extension:
If you need to modify multiple global variables in a function, you can use
global a, b
# 还可以用多次global声明都是可以的
global a
global b