三,函数与函数式编程
1,函数与过程
①先看代码:
# 函数
def process():
"""testing""" # 文档描述,表明你要写的是什么内容(必须要写)
print("in the process!")
return 0
# 过程
def function():
"""testing1"""
print("in the function!")
a = process()
b = function()
G:\Project1\venv\Scripts\python.exe G:/Project1/function.py
in the process!
in the function!
Process finished with exit code 0
是不是阔以一目了然的看清楚它们之间的区别:函数有返回值,而过程却没有
②再看代码:
# 函数
def process():
"""testing""" # 文档描述,表明你写的是什么内容
print("in the process!")
return 0
# 过程
def function():
"""testing1"""
print("in the function!")
a = process()
b = function()
print("from process return is %s" % a)
print("from function return is %s" % b)
G:\Project1\venv\Scripts\python.exe G:/Project1/function.py
in the process!
in the function!
from process return is 0
from function return is None
Process finished with exit code 0
阔以看出,函数有返回值就返回了0,而过程没有就返回了none
③创建一个名为lianxi的文本文件
看代码:
import time
def logger():
time_format = "%Y-%m-%d %x"
time_current = time.strftime(time_format)
with open("lianxi", "a+", encoding="utf-8") as f:
f.write("%s hello!thank you!!!\n" % time_current)
def test1():
print("in the test1")
logger()
def test2():
print("in the test2")
logger()
def test3():
print("in the test3")
logger()
test1()
test2()
test3()
G:\Project1\venv\Scripts\python.exe G:/Project1/function.py
in the test1
in the test2
in the test3
Process finished with exit code 0
打开lianxi则看到:
嘻嘻嘻,不禁感叹道,Python真有意思!
通过②和③,细心地你就会发现使用函数的三大优点:
1,代码重用,
2,保持一致性
3,可扩展性
2,函数返回值
看代码:
def test1():
print("this is test1!")
# 无返回值
def test2():
print("this is test2!")
return 0
# 返回值为0
def test3():
print("this is test3!")
return 1, ["pig", "dog", "cat"], {"name": "hpl"}
# 随便定义一些返回值,包括数字,列表,字典(不看运行结果,你感觉这里阔以返回吗?)
a = test1()
b = test2()
c = test3()
print(a)
print(b)
print(c)
G:\Project1\venv\Scripts\python.exe G:/Project1/function.py
this is test1!
this is test2!
this is test3!
None
0
(1, ['pig', 'dog', 'cat'], {'name': 'hpl'})
Process finished with exit code 0
总结:
没有返回值时,返回None
返回值只有一个时,将返回那个值
返回值为多个时,返回tuple(元组)
3,函数调用
①看代码:
def test(x, y):
print("I like you!And you like me!")
print(x)
print(y)
a = 1
b = 2
test(2, 3) # 与形参一一对应
test(y=2, x=3)
test(y=a, x=b)
test(4, y=5)
G:\Project1\venv\Scripts\python.exe G:/Project1/function.py
I like you!And you like me!
2
3
I like you!And you like me!
3
2
I like you!And you like me!
2
1
I like you!And you like me!
4
5
Process finished with exit code 0
这里要仔细看,仔细想。
②再看代码:
def test(*args): # 以*开始就阔以同时接受多个实参,调用时就会放到元组里面
print(args)
test(1, 2, 3, 4, 5)
test([1, 2, 3, 4, 5, 6])
test(*[1, 2, 3, 4, 5])
print("<<<<<<<<----------->>>>>>>>")
def test1(x, *args):
print(x)
print(args)
test1(1, 2, 3, 4, 5,6, 7)
G:\Project1\venv\Scripts\python.exe G:/Project1/function.py
(1, 2, 3, 4, 5)
([1, 2, 3, 4, 5, 6],)
(1, 2, 3, 4, 5)
<<<<<<<<----------->>>>>>>>
1
(2, 3, 4, 5, 6, 7)
Process finished with exit code 0
这个能看明白吧!
③
# 接收字典
def test(**kwargs): # **kwards:把n个关键字参数转换成字典的形式
print(kwargs)
print(kwargs["name"])
print(kwargs["age"])
print(kwargs["sex"])
test(name="hpl", age=18, sex="f")
print("<<<<<<<<-----1------>>>>>>>>")
def test2(name, **kwargs):
print(name)
print(kwargs)
test2("hpl", age=18, sex="n")
print("<<<<<<<<-----2------>>>>>>>>")
def test3(name, age=18, **kwargs):
print(name)
print(kwargs)
print(age)
test3("hpl", sex="m", hobby="tesla", )
print("<<<<<<<<-------3------>>>>>>>>>>")
test3("hpl", sex="m", hobby="tesla", age=3)
print("<<<<<<<<-------4------>>>>>>>>>>")
test3("hpl", 20, sex="m", hobby="tesla")
print("<<<<<<<<-------5------>>>>>>>>>>")
test3("hpl", age=22, sex="m", hobby="tesla")
print("<<<<<<<<-----6------>>>>>>>>")
def test4(name, age=18, *args, **kwargs):
print(name)
print(args)
print(kwargs)
print(age)
test4("hpl", age=22, sex="m", hobby="tesla")
结果为:
G:\Project1\venv\Scripts\python.exe G:/Project1/function.py
{'name': 'hpl', 'age': 18, 'sex': 'f'}
hpl
18
f
<<<<<<<<-----1------>>>>>>>>
hpl
{'age': 18, 'sex': 'n'}
<<<<<<<<-----2------>>>>>>>>
hpl
{'sex': 'm', 'hobby': 'tesla'}
18
<<<<<<<<-------3------>>>>>>>>>>
hpl
{'sex': 'm', 'hobby': 'tesla'}
3
<<<<<<<<-------4------>>>>>>>>>>
hpl
{'sex': 'm', 'hobby': 'tesla'}
20
<<<<<<<<-------5------>>>>>>>>>>
hpl
{'sex': 'm', 'hobby': 'tesla'}
22
<<<<<<<<-----6------>>>>>>>>
hpl
()
{'sex': 'm', 'hobby': 'tesla'}
22
Process finished with exit code 0
细细看,细细品!!!
四,全局变量与局部变量
看代码理解:
# variable(变量)
school = "xi'an university" # 全局变量
def change_name(name):
school = "middle school" # 局部变量
print("before change is:", name, school)
name = "hpl" # 局部变量
print("after name is:", name)
name = "HPL" # 全局变量
change_name(name)
print(name)
print(school)
G:\Project1\venv\Scripts\python.exe G:/Project1/function.py
before change is: HPL middle school
after name is: hpl
HPL
xi'an university
Process finished with exit code 0
是不是还是挺容易理解的!!!
再看这段代码:
# 这种方式强烈不建议使用(樯橹灰飞烟灭)
def change_name():
global name # 将变量name用作全局变量
name = "hpl"
change_name()
print(name)
G:\Project1\venv\Scripts\python.exe G:/Project1/function.py
hpl
Process finished with exit code 0
五,递归
# 递归
def calc(n):
print(n)
if int(n/2) > 0:
return calc(int(n/2))
calc(100)
G:\Project1\venv\Scripts\python.exe G:/Project1/function.py
100
50
25
12
6
3
1
Process finished with exit code 0
总结:
1,递归有明确的结束条件。
2,问题规模每递归一次都应该比上一次的问题规模有所减少。
3,效率低
六,高阶函数
# 高阶函数
def add(a, b, f):
return f(a) + f(b)
res = add(3, -5, abs)
print(res)
G:\Project1\venv\Scripts\python.exe G:/Project1/function.py
8
Process finished with exit code 0
七,字符编码
# 任何码之间的转换都要经过Unicode(万国码),utf-8是Unicode的一个扩展集,
# 也阔以说Unicode包含utf-8,gb2312也认识Unicode
# encode()表示解码,decode()表示编码
a = "你好,小明!"
print(a.encode("gbk"))
print(a.encode("utf-8"))
print(a.encode("utf-8").decode("utf-8"))
print(a.encode("utf-8").decode("utf-8").encode("gb2312"))
print(a.encode("utf-8").decode("utf-8").encode("gb2312").decode("gb2312"))
G:\Project1\venv\Scripts\python.exe G:/Project1/first_three_weeks/day5.py
b'\xc4\xe3\xba\xc3\xa3\xac\xd0\xa1\xc3\xf7\xa3\xa1'
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe5\xb0\x8f\xe6\x98\x8e\xef\xbc\x81'
你好,小明!
b'\xc4\xe3\xba\xc3\xa3\xac\xd0\xa1\xc3\xf7\xa3\xa1'
你好,小明!
Process finished with exit code 0
这里要好好地看!!!
好了,这周的学习内容就到此为止,望各位看客大佬发现有不足或错误能留言相告,臣不胜感激!!!
链接: 基础三(1).