Python 3 学习笔记(四)----字符编码、函数与参数

一、字符编码与转码

1.在python2默认编码是ASCII, python3里默认是unicode
2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间
3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

在python2.x中:

 1 -*- coding:UTF-8 -*-
 2 import sys
 3 print(sys.getdefaultencoding())  #查看系统的默认编码
 4     
 5 msg = "学习使人进步"
 6 msg_gbk = msg.decode("UTF-8").encode("gbk")   #由"UTF-8"格式转到"gbk",首先要将UTF-8解码成unicode,再由unicode编码成gbk。在解码时,要声明现在自己是什么格式的
 7 msg_gb2312 = msg_gbk.decode("gbk").encode("gb2312")
 8     
 9 print(msg)
10 print(msg_gbk)
11 print(msg_gb2312)

在python3.x中:

 1 #-*- coding:gbk -*-
 2 
 3 import sys
 4 print(sys.getdefaultencoding())
 5 #如果文件编码改成gbk,需要在头声明是gbk(就是pycharm右下角)
 6 msg = "三体"   #这个"三体"的格式还是Unicode,因为改变的只是文件的编码,python的编码总是Unicode
 7 print(msg)
 8 
 9 
10 '''
11 #由UTF-8格式转到gbk格式
12 
13 s = "科幻小说"
14 print(s.encode())    #打印utf-8的编码
15 s_gbk = s.encode("gbk")
16 print(s_gbk)   #默认就是unicode,不用再decode(UTF-8是Unicode的扩展集)
17 
18 #由gbk格式再转回UTF-8格式
19 
20 s_utf8 = s_gbk.decode("gbk").encode("utf-8")
21 print(s_utf8)
22 '''

二、函数与函数式编程

编程的方法:

1.象:特点-->类-->class
2.面向过程:特点-->过程-->def
3.函数式编程:-->函数-->def

函数的定义:

数学中:一般的,在一个变化过程中,假设有两个变量x、y,如果对于任意一个x都有唯一确定的一个y和它对应,那么就称x是自变量,y是x的函数。x的取值范围叫做这个函数的定义域,相应y的取值范围叫做函数的值域。

编程中:函数是逻辑结构化和过程化的一种编程方法。

Python中的函数定义法:

 1 def test(x):
 2     '''The function definitions'''
 3     x+=1
 4     return x
 5             
 6 
 7 def:定义函数的关键字
 8 test:函数名
 9 ():内可定义形参
10 '''''':文档描述(非必要,但是强烈建议为你的函数添加描述信息)
11 x+=1:泛指代码块或程序处理逻辑
12 return:定义返回值

函数型:

1 def func1():
2     '''test1'''
3     print("this is func1")
4     return 0
5 

过程型(将程序中每一种功能都定义为def包含的过程当中,使用的时候直接用函数名+()使用)

1 def func2():
2     '''test2'''
3     print("this is func2")
4 #过程就是没有返回值的函数
5     
6 y = func2() #调用函数

使用函数替换重复的代码:

 1 import time
 2 def logger():
 3     time_format = "%Y-%m-%d %X" #X代表时分秒
 4     time_now = time.strftime(time_format)
 5     with open("log.txt","a+") as f:
 6         f.write("%s The end
" %time_now)
 7 '''
 8 def test1():
 9     '''testing'''
10     print("start append log...")
11     with open("log.txt","a+") as f:
12     f.write("The end")
13     
14 def test2():
15     '''testing'''
16     print("start append log...")
17     with open("log.txt","a+") as f:
18     f.write("The end")
19     
20 def test3():
21     '''testing'''
22     print("start append log...")
23     with open("log.txt","a+") as f:
24     f.write("The end")
25 '''
26 
27 def test1():
28     '''testing'''
29     print("start append log...")
30     logger()
31 
32 def test2():
33     '''testing'''
34     print("start append log...")
35     logger()
36 
37 def test3():
38     '''testing'''
39     print("start append log...")
40     logger()
41 
42 x = test1()
43 y = test2()
44 z = test3()

函数三大优点:

1.代码重用
2.保持一致性
3.可扩展性

函数返回值:

 1 def test1():
 2     '''return test'''
 3     msg = "刘慈欣 地球往事"
 4     print(msg)
 5 
 6 def test2():
 7     '''return test'''
 8     msg = "刘慈欣 地球往事"
 9     print(msg)
10     return msg
11 
12 a = test1()
13 b = test2()
14 
15 print("返回值为 [%s]" %a)
16 print("返回值为 [%s]" %b)
17 
18 #当一个函数(过程型)没有使用return显示的定义返回值时,python解释器会隐式的返回None,所以在python中即便是过程也可视作函数
19 
20     返回值数=0;返回None
21     返回值数=1(例如"0");返回object
22     返回值数>1(例如"0","[0,1,2.3]"多于1项);返回tupl    
23 
24 #为什么要有返回值?因为想要一个函数的执行结果

三、参数

形参和实参:

形参:形式参数,不是实际存在,是虚拟变量。在定义函数和函数体时使用形参,目的是在函数调用时接收实参
实参:实际参数,调用函数时传给函数的参数,可以是常量、变量、表达式、函数,传给形参

区别:形参时虚拟的,不占用内存空间,形参变量只有在调用时才分配内存单元,实参时一个变量,占用内存空间,实参传给形参,不能形参传给实参。

位置参数和关键字:(标准调用:实参与形参位置一一对应;关键字调用:位置无需固定)

1 def test(x,y,z):  #这里xyz叫形参
2     print(x)
3     print(y)
4     print(z)
5 
6 test(1,3,5)  #这里135叫实参。这种方式叫位置参数
7 test(y=1,x=4,z=5)  #关键字参数
8 test(1,3,z=6)   #这种写法也可以,但是关键字必须要在位置参数之后,并且不能重复

默认参数:

 1 def test1(x,z,y=2):
 2     print(x)
 3     print(y)
 4     print(z)
 5 
 6 test1(1,5)
 7 test1(1,3)
 8 
 9 #默认参数特点:调用函数的时候,默认参数非必需传递
10 #默认参数用途:软件安装时的默认选项,连接数据库时的默认端口

参数组:

 1 def test2(*args):    # *args只能接收位置参数,不能接收关键词参数
 2     print(args)
 3 
 4 test2(1,2,3,6,8,9)
 5 test2(*[2,4,6,2])   #args=tuple[2,4,6,2]
 6 
 7 def test3(x,*args):
 8     print(x)
 9     print(args)
10 
11 test3(1,2,3,4,5,6,7,8,9,)   #这里1传给x,剩下的变成元组传给args
12 
13 def test4(**kwargs):    # **kwargs:把N个关键字参数转换成字典的方式
14     print(kwargs)
15     print(kwargs["name"])
16     print(kwargs["age"])
17     print(kwargs["IQ"])
18 
19 test4(name="Irlo",age=26,sex="F",IQ=220)
20 test4(**{"name":'Irlo',"age":'26',"IQ":'220'})
21 
22 
23 def test5(name,**kwargs):
24     print(name)
25     print(kwargs)
26 
27 test5("Irlo") #如果不给kwargs传东西则返回一个空字典
28 test5("hehe",age=26,IQ=220) # **kwargs不能接收位置参数
29 
30 
31 def test6(name,age=26,**kwargs):   #参数组必须放在最后
32     print(name)
33     print(age)
34     print(kwargs)
35 
36 test6("Irlo",35,IQ=220,sex="m")  #默认参数可以用位置参数的方式赋值,或用关键字的方式赋值,如果不赋值则使用默认参数
37 
38 
39 def test7(name,age=26,*args,**kwargs):
40     print(name)
41     print(age)
42     print(args)
43     print(kwargs)
44     logger("Force")
45 
46 def logger(source):    #函数test7中嵌套一个函数logger,该logger的声明必须要早于函数test7的调用,否则报错
47     print("from %s" %source)
48 
49 test7("Irlo",54,5,IQ=220,sex="M")
原文地址:https://www.cnblogs.com/consort/p/7350744.html