1.函数的基本定义
def 函数名称(参数)
执行语句
return 返回值
def : 定义函数的关键字;
函数名称:顾名思义,就是函数的名字,可以用来调用函数,不能使用关键字来命名,做好是用这个函数的功能的英文名命名,可以采用驼峰法与下划线法;
参数:用来给函数提供数据,有形参和实参的区分;
执行语句:也叫函数体,用来进行一系列的逻辑运算;
返回值:执行完函数后,返回给调用者的数据,默认为None,所以没有返回值时,可以不写return。
2.函数的普通参数
最直接的一对一关系的参数,如:
def fun_ex(a,b): #a,b是函数fun_ex的形式参数,也叫形参
sum=a+b
print('sum =',sum)
fun_ex(1,3) #1,3是函数fun_ex的实际参数,也叫实参
#运行结果
sum = 4
3.函数的默认参数
给参数定义一个默认值,如果调用函数时,没有给指定参数,则函数使用默认参数,默认参数需要放在参数列表的最后,如:
def fun_ex(a,b=6): #默认参数放在参数列表最后,如b=6只能在a后面
sum=a+b
print('sum =',sum)
fun_ex(1,3)
fun_ex(1)
#运行结果
sum = 4
sum = 7
4.函数的动态参数
不需要指定参数是元组或字典,函数自动把它转换成元组或字典,如:
1 #转换成元组的动态参数形式,接受的参数需要是可以转成元组的形式,就是类元组形式的数据,如数值,列表,元组。
2
3 def func(*args):
4 print(args,type(args))
5
6 func(1,2,3,4,5)
7
8 date_ex1=('a','b','c','d')
9 func(*date_ex1)
10
11 #运行结果
12 (1, 2, 3, 4, 5) <class 'tuple'>
13 ('a', 'b', 'c', 'd') <class 'tuple'>
1 #转换成字典的动态参数形式,接收的参数要是能转换成字典形式的,就是类字典形式的数据,如键值对,字典
2
3 def func(**kwargs):
4 print(kwargs,type(kwargs))
5
6 func(a=11,b=22)
7
8 date_ex2={'a':111,'b':222}
9 func(**date_ex2)
10
11 #运行结果
12 {'b': 22, 'a': 11} <class 'dict'>
13 {'b': 222, 'a': 111} <class 'dict'>
1 #根据传的参数转换成元组和字典的动态参数形式,接收的参数可以是任何形式。
2 def func(*args,**kwargs):
3 print(args, type(args))
4 print(kwargs,type(kwargs))
5
6 func(123,321,a=999,b=666)
7
8 date_ex3={'a':123,'b':321}
9 func(**date_ex3)
10
11 #运行结果
12 (123, 321) <class 'tuple'>
13 {'b': 666, 'a': 999} <class 'dict'>
14 () <class 'tuple'>
15 {'b': 321, 'a': 123} <class 'dict'>
5.函数的返回值
运行一个函数,一般都需要从中得到某个信息,这时就需要使用return来获取返回值,如:
def fun_ex(a,b):
sum=a+b
return sum #返回sum值
re=fun_ex(1,3)
print('sum =',re)
#运行结果
sum = 4
6.lambda表达式
用来表达简单的函数,如:
#普通方法定义函数
def sum(a,b):
return a+b
sum=sum(1,2)
print(sum)
#lambda表达式定义函数
myLambda = lambda a,b : a+b
sum=myLambda(2,3)
print(sum)
#运行结果
3
5
7.内置函数
1)内置函数列表
官方说明文档地址:https://docs.python.org/3/library/functions.html
中文版官方说明文档地址:http://python.usyiyi.cn/translate/python_352/index.html
2)内置函数功能
运算类内置函数:
ads(x): 取绝对值,参数是复数,返回它的模;
max
(iterable, *[, key, default])/max
(arg1, arg2, *args[, key]): 取所有元素的最大值;
min
(iterable, *[, key, default])/min
(arg1, arg2, *args[, key]): 取所有元素的最小值;
divmod
(a, b): 返回a,b两数的商和余数的一对数字(可用于分页显示功能);
实例:
1 a=abs(-10)
2 b=abs(3)
3 print(a)
4 print(b)
5
6 #运行结果
7 10
8 3
1 a=max(1,2,*(3,4))
2 b=max(*(1,2),*[5,6])
3 print(a)
4 print(b)
5
6 #运行结果
7 4
8 6
1 a=min(1,2,*(3,4))
2 b=min(*(0,1,2),*[5,6])
3 print(a)
4 print(b)
5
6 #运行结果
7 1
8 0
1 a=divmod(5,2)
2 print(a)
3
4 #运行结果
5 (2, 1)
类型转换类内置函数:
int(x): 把数据转换成整数型;
ascii
(object): 类似repr(),返回一个可打印的对象字符串方式表示。当遇到非ASCII码时,就会输出\x,\u或\U等字符来表示;
bin
(x): 将一个整数转化成一个二进制字符串;
class bool
([x]): 根据给的数据,返回一个布尔值,True
或 False;
class bytearray
([source[, encoding[, errors]]]): 返回一个byte数组;
class bytes
([source[, encoding[, errors]]]): 返回一个新的字节对象,是一个在 0<= x < 256
之间的不可变的整数序列;
chr
(i): 返回表示Unicode码点为整数i的字符的字符串,它是ord()
的逆操作。参数的有效范围为0到1,114,111(基址16中的0x10FFFF)。如果i超出该范围,则会引发ValueError
报错;
compile
(source, filename, mode, flags=0, dont_inherit=False, optimize=-1): 将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值;
class complex
([real[, imag]]): 返回值形式为real + imag * j的复数,或将字符串(数字形式的字符串)或数字转换为复数;
enumerate
(iterable, start=0): 返回一个枚举对象。iterable 必须是一个序列、一个迭代器,或者其它某种支持迭代的对象;
eval
(expression, globals=None, locals=None): 还原字符串中的数据结构;
实例:
1 a=3.14159
2 b="12"
3 c=int(a)
4 d=int(b)
5 print(a,type(a))
6 print(b,type(b))
7 print(c,type(c))
8 print(d,type(d))
9
10 运行结果
11 3.14159 <class 'float'>
12 12 <class 'str'>
13 3 <class 'int'>
14 12 <class 'int'>
1 print(ascii('a'))
2 print(ascii(999999))
3 print(ascii('\11'))
4 print(ascii('\200'))
5
6 #运行结果
7 'a'
8 999999
9 '\t'
10 '\x80'
1 a=bin(5)
2 print(a,type(a))
3
4 #运行结果
5 0b101 <class 'str'>
1 a=bool(5)
2 b=bool(0)
3 print(a)
4 print(b)
5
6 #运行结果
7 True
8 False
1 #如果source为空,则返回一个长度为0的字节数组
2 a=bytearray()
3 print(a,len(a))
4
5 #如果source为字符串,则按照指定的encoding将字符串转换为字节序列
6 b=bytearray('abcd中文','utf-8 ')
7 print(b)
8
9 #如果source为整数,则返回一个长度为source整数的初始化数组
10 c=bytearray(5)
11 print(c,len(c))
12
13 #如果source为可迭代类型,则元素必须为[0 ,255]中的整数
14 d=bytearray([9,8,7])
15 print(d)
16
17 #运行结果
18 bytearray(b'') 0
19 bytearray(b'abcd\xe4\xb8\xad\xe6\x96\x87')
20 bytearray(b'\x00\x00\x00\x00\x00') 5
21 bytearray(b'\t\x08\x07')
1 a='abcd'
2 b='中文'
3
4 #转换成字节编码
5 c=bytes(a,encoding='gbk')
6 d=bytes(b,encoding='utf-8')
7 e=bytes(b,encoding='gbk')
8
9 #解码过程,用什么规则编码,就用什么解码
10 f=d.decode('utf-8')
11 h=e.decode('gbk')
12
13 #打印信息
14 print(c)
15 print(d)
16 print(e)
17 print(f)
18 print(h)
19
20 #运行结果
21 '''
22 b'abcd'
23 b'\xe4\xb8\xad\xe6\x96\x87'
24 b'\xd6\xd0\xce\xc4'
25 中文
26 中文
27 '''
1 print(chr(65))
2 print(chr(0))
3 print(chr(33))
4 print(chr(1114111))
5
6 #运行结果
7 A
8
9 !
10 ????
1 '''
2 参数source:字符串或者AST(Abstract Syntax Trees)对象。
3
4 参数filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。
5
6 参数model:指定编译代码的种类。可以指定为 ‘exec’,’eval’,’single’。
7 '''
8
9 code_one = "print('hello')"
10 a = compile(code_one,'','exec')
11 exec(a)
12
13 code_two ="print(1+2*3)"
14 b = compile(code_two,'','eval')
15 eval(b)
16 print(b)
17
18 #运行结果
19 hello
20 7
21 <code object <module> at 0x005419D0, file "", line 1>
1 print(complex(1,2))
2
3 #如果省略imag,则默认为零,构造函数会像int和float一样进行转换。如果省略这两个参数,则返回0j。
4 print(complex(1))
5
6 #如果第一个参数为字符串,则不需要指定第二个参数。
7 print(complex('1'))
8
9 #当从字符串转化成复数的时候,字符串中+或者-两边不能有空白,如下不能写成"1 + 2j",应该是"1+2j",否则会报错
10 print(complex('1+2j'))
11
12 #运行结果
13 (1+2j)
14 (1+0j)
15 (1+0j)
16 (1+2j)
1 str='abcd'
2 print(list(enumerate(str)))
3 print(dict(enumerate(str)))
4
5 #运行结果
6 [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
7 {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
1 x=1
2 print(eval('x+1'))
3
4 dic={'a':1,'b':2}
5 str=str(dic)
6 print(str,type(str))
7 ev=eval(str)
8 print(ev,type(ev))
9
10 #运行结果
11 2
12 {'a': 1, 'b': 2} <class 'str'>
13 {'a': 1, 'b': 2} <class 'dict'>
判断类内置函数:
all
(iterable): 判断iterable序列中是否所有元素都为真,或整个序列为空,满足条件则返回True;
any
(iterable): 判断iterable序列中是否任意一个元素为真,满足条件则返回True,这里整个序列为空,返回False;
callable
(object): 判断对象object是否可调用。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功;
实例:
1 a=[]
2 b=[1,2,'']
3 c=[0,1,2,3]
4 d=[1,2,3]
5 print(all(a))
6 print(all(b))
7 print(all(c))
8 print(all(d))
9
10 #运行结果
11 True
12 False
13 False
14 True
1 a=[]
2 b=[1,2,'']
3 c=[0,0,0,1]
4 d=[0,0,0]
5 print(any(a))
6 print(any(b))
7 print(any(c))
8 print(any(d))
9
10 #运行结果
11 False
12 True
13 True
14 False
1 #基本数据类型callable情况
2 print('基本数据类型callable情况')
3 print(callable(1))
4 print(callable('string'))
5
6 #函数的callable情况
7 print('#函数的callable情况')
8 def sum(a,b):
9 return a+b
10 a=sum(1,2)
11 print(callable(sum))
12 print(callable(a))
13
14 #类的callable情况
15 print('#类的callable情况')
16 class ex_1:
17 def add(self):
18 return 0
19 b=ex_1()
20 print(callable(ex_1))
21 print(callable(b))
22 class ex_2:
23 def __call__(self, *args, **kwargs):
24 return 0
25 c=ex_2()
26 print(callable(ex_2))
27 print(callable(c)) #类是可调用的,而类的实例实现了__call__()方法才可调用。
28
29 #运行结果
30 '''
31 基本数据类型callable情况
32 False
33 False
34 #函数的callable情况
35 True
36 False
37 #类的callable情况
38 True
39 False
40 True
41 True
42 '''
IO操作类内置函数:
input
([prompt]): 获取用户的输入,获取的数据会转换成字符串;
实例:
1 a=input('fist input :')
2 b=input('second input :')
3 print(a,type(a))
4 print(b,type(b))
5
6 #运行结果
7 fist input :as
8 second input :12
9 as <class 'str'>
10 12 <class 'str'>
基础数据类型内置函数:
class dict
(): 创建字典。
其他内置函数:
help
([object]): 调用内置帮助系统;
classmethod
(function): 用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法,类方法既可以直接类调用(C.f()),也可以进行实例调用(C().f());
delattr
(object, name): 删除object对象的某个属性;
dir
([object]): 显示函数内置属性和方法;
实例:
1 help(int)
2
3 #运行结果
4 Help on class int in module builtins:
5
6 class int(object)
7 | int(x=0) -> integer
8 | int(x, base=10) -> integer
9 |
10 | Convert a number or string to an integer, or return 0 if no arguments
11 | are given. If x is a number, return x.__int__(). For floating point
12 | numbers, this truncates towards zero.
13 |
14 | If x is not a number or if base is given, then x must be a string,
15 | bytes, or bytearray instance representing an integer literal in the
16 | given base. The literal can be preceded by '+' or '-' and be surrounded
17 | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
18 | Base 0 means to interpret the base from the string as an integer literal.
19 | >>> int('0b100', base=0)
20 | 4
21 |
22 | Methods defined here:
23 |
24 | __abs__(self, /)
25 | abs(self)
26 |
27 | __add__(self, value, /)
28 | Return self+value.
29 |
30 | __and__(self, value, /)
31 | Return self&value.
32 |
33 | __bool__(self, /)
34 | self != 0
35 |
36 | __ceil__(...)
37 | Ceiling of an Integral returns itself.
38 |
39 | __divmod__(self, value, /)
40 | Return divmod(self, value).
41 |
42 | __eq__(self, value, /)
43 | Return self==value.
44 |
45 | __float__(self, /)
46 | float(self)
47 |
48 | __floor__(...)
49 | Flooring an Integral returns itself.
50 |
51 | __floordiv__(self, value, /)
52 | Return self//value.
53 |
54 | __format__(...)
55 | default object formatter
56 |
57 | __ge__(self, value, /)
58 | Return self>=value.
59 |
60 | __getattribute__(self, name, /)
61 | Return getattr(self, name).
62 |
63 | __getnewargs__(...)
64 |
65 | __gt__(self, value, /)
66 | Return self>value.
67 |
68 | __hash__(self, /)
69 | Return hash(self).
70 |
71 | __index__(self, /)
72 | Return self converted to an integer, if self is suitable for use as an index into a list.
73 |
74 | __int__(self, /)
75 | int(self)
76 |
77 | __invert__(self, /)
78 | ~self
79 |
80 | __le__(self, value, /)
81 | Return self<=value.
82 |
83 | __lshift__(self, value, /)
84 | Return self<<value.
85 |
86 | __lt__(self, value, /)
87 | Return self<value.
88 |
89 | __mod__(self, value, /)
90 | Return self%value.
91 |
92 | __mul__(self, value, /)
93 | Return self*value.
94 |
95 | __ne__(self, value, /)
96 | Return self!=value.
97 |
98 | __neg__(self, /)
99 | -self
100 |
101 | __new__(*args, **kwargs) from builtins.type
102 | Create and return a new object. See help(type) for accurate signature.
103 |
104 | __or__(self, value, /)
105 | Return self|value.
106 |
107 | __pos__(self, /)
108 | +self
109 |
110 | __pow__(self, value, mod=None, /)
111 | Return pow(self, value, mod).
112 |
113 | __radd__(self, value, /)
114 | Return value+self.
115 |
116 | __rand__(self, value, /)
117 | Return value&self.
118 |
119 | __rdivmod__(self, value, /)
120 | Return divmod(value, self).
121 |
122 | __repr__(self, /)
123 | Return repr(self).
124 |
125 | __rfloordiv__(self, value, /)
126 | Return value//self.
127 |
128 | __rlshift__(self, value, /)
129 | Return value<<self.
130 |
131 | __rmod__(self, value, /)
132 | Return value%self.
133 |
134 | __rmul__(self, value, /)
135 | Return value*self.
136 |
137 | __ror__(self, value, /)
138 | Return value|self.
139 |
140 | __round__(...)
141 | Rounding an Integral returns itself.
142 | Rounding with an ndigits argument also returns an integer.
143 |
144 | __rpow__(self, value, mod=None, /)
145 | Return pow(value, self, mod).
146 |
147 | __rrshift__(self, value, /)
148 | Return value>>self.
149 |
150 | __rshift__(self, value, /)
151 | Return self>>value.
152 |
153 | __rsub__(self, value, /)
154 | Return value-self.
155 |
156 | __rtruediv__(self, value, /)
157 | Return value/self.
158 |
159 | __rxor__(self, value, /)
160 | Return value^self.
161 |
162 | __sizeof__(...)
163 | Returns size in memory, in bytes
164 |
165 | __str__(self, /)
166 | Return str(self).
167 |
168 | __sub__(self, value, /)
169 | Return self-value.
170 |
171 | __truediv__(self, value, /)
172 | Return self/value.
173 |
174 | __trunc__(...)
175 | Truncating an Integral returns itself.
176 |
177 | __xor__(self, value, /)
178 | Return self^value.
179 |
180 | bit_length(...)
181 | int.bit_length() -> int
182 |
183 | Number of bits necessary to represent self in binary.
184 | >>> bin(37)
185 | '0b100101'
186 | >>> (37).bit_length()
187 | 6
188 |
189 | conjugate(...)
190 | Returns self, the complex conjugate of any int.
191 |
192 | from_bytes(...) from builtins.type
193 | int.from_bytes(bytes, byteorder, *, signed=False) -> int
194 |
195 | Return the integer represented by the given array of bytes.
196 |
197 | The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
198 |
199 | The byteorder argument determines the byte order used to represent the
200 | integer. If byteorder is 'big', the most significant byte is at the
201 | beginning of the byte array. If byteorder is 'little', the most
202 | significant byte is at the end of the byte array. To request the native
203 | byte order of the host system, use `sys.byteorder' as the byte order value.
204 |
205 | The signed keyword-only argument indicates whether two's complement is
206 | used to represent the integer.
207 |
208 | to_bytes(...)
209 | int.to_bytes(length, byteorder, *, signed=False) -> bytes
210 |
211 | Return an array of bytes representing an integer.
212 |
213 | The integer is represented using length bytes. An OverflowError is
214 | raised if the integer is not representable with the given number of
215 | bytes.
216 |
217 | The byteorder argument determines the byte order used to represent the
218 | integer. If byteorder is 'big', the most significant byte is at the
219 | beginning of the byte array. If byteorder is 'little', the most
220 | significant byte is at the end of the byte array. To request the native
221 | byte order of the host system, use `sys.byteorder' as the byte order value.
222 |
223 | The signed keyword-only argument determines whether two's complement is
224 | used to represent the integer. If signed is False and a negative integer
225 | is given, an OverflowError is raised.
226 |
227 | ----------------------------------------------------------------------
228 | Data descriptors defined here:
229 |
230 | denominator
231 | the denominator of a rational number in lowest terms
232 |
233 | imag
234 | the imaginary part of a complex number
235 |
236 | numerator
237 | the numerator of a rational number in lowest terms
238 |
239 | real
240 | the real part of a complex number
1 class C:
2 @classmethod
3 def f(self):
4 print('this is class method')
5 print(C.f())
6 print(C().f())
7
8 class D:
9 def f(self):
10 print('this is not a class method')
11 print(D().f()) #这里不能用D.f()
12
13 #运行结果
14 this is class method
15 None
16 this is class method
17 None
18 this is not a class method
19 None
1 class Dog :
2 def __init__(self,name,age):
3 self.name=name
4 self.age=age
5 dahuang = Dog('dahuang',2)
6 print(dir(dahuang))
7 delattr(dahuang,"age")
8 print(dir(dahuang))
9
10 #运行结果
11 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']
12 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']
1 print(dir(int))
2
3 #运行结果
4 ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']