6.函数基础和函数参数

             函数基础            

函数的定义及调用

def func():          #def 函数名(参数):
    pass                      #跳过
func()                  #函数的调用

1、函数的定义

def 函数名(参数):

  pass

函数名命名规则: 字母、数字和下划线组成,和 变量命名规则一致

2、函数的调用

          函数名()

            函数参数             

函数参数的定义

1、必备参数

def func(x):
    pass

2、默认参数:

def func(x,y=None)
    pass

3、不定长参数:

def func(*args,**kwargs):
    pass

参数的调用: 1、通过位置传递参数(未命名参数) 2、通过关键字传递参数(命名参数)

在python中参数无类型,参数可以接受任意对象, 只有函数中代码才会对参数类型有限制

函数参数调用演示

 1、必备参数:

在函数调用的时候,必备参数必须要传入

def func(x):
    print(x)
func(1)

2、默认参数:

在函数调用的时候,默认参数可以不传入值,不传入值时,会使用默认参数

def func(x,y=None):
    print(x)
    print(y)
func(1)
func(1,2)

3、不定长参数:

在函数调用的时候,不定长参数可以不传入,也可以传入任意长度。 其中定义时,元组形式可以放到参数最前面,字典形式只能放到最后面

def func(*args,**kwargs):
    print(args)      #以元组形式保存,接受的是多传的位置参数
    print(kwargs)          #以字典形式保存接受的多传的关键字参数
func(1,2,3,a=4,b=5,c=6)
(1, 2, 3)
{'c': 6, 'a': 4, 'b': 5}

                拆包               

def sum_num(a,b,tt=99,*args,**kwargs):
    print(a)
    print(b)
    print(tt)
    print(args)
    print(kwargs)
sum_num(*(1,2,3,4),**{'aa':11,'cc':22},bb='hello')

         常见内置函数         

Python中简单内置函数

1、内置对象查看

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

2、常见函数:

len 求长度

>> li = [1,2,3,4,5]
>>> len(li)
5

min 求最小值

>>> min(li)
1

max 求最大值

>>> max(li)
5

sorted排序

>>> li = [1,23,1,34,565,34,767,53,7,2]
>>> li.sort()
>>> li
[1, 1, 2, 7, 23, 34, 34, 53, 565, 767]
>>> li = [1,23,1,34,565,34,767,53,7,2]
>>> li1 = sorted(li)
>>> li1
[1, 1, 2, 7, 23, 34, 34, 53, 565, 767]
>>> 
#sort()无返回值,直接改变原列表。
#sorted()有返回值,不改变原列表

reversed 反向

>>> reversed(li)
<list_reverseiterator object at 0xb717e94c>    #返回对象需转换成列表,不改变原列表
>>> list(reversed(li))
[2, 7, 53, 767, 34, 565, 34, 1, 23, 1]
>>> li.reverse()                                            #直接改变原列表
>>> li
[2, 7, 53, 767, 34, 565, 34, 1, 23, 1]

sum 求和

>>> sum([1,2,3,4,5,6,5,4,3])
33

3、进制转换函数:

bin 转换为二进制

>>> bin(12)
'0b1100'
>>> bin(22)
'0b10110'

oct 转换为八进制

>>> oct(22)
'0o26'

hex 转换为十六进制

>>> hex(22)
'0x16'

ord 字符转ASCII码

>>> ord('a')
97
>>> ord('A')
65

chr ASCII码转字符

>>> chr(65)
'A'
>>> chr(97)
'a'

Python中简单内置函数

1、enumerate  : 同时列出数据和数据下标,一般用在 for 循环当中

返回一个对象,用变量去接收,转换成列表,元素值和下标一一对应取出,可通过for循环取出

>>> li = [111,222,333,444,555,666,777]
>>> enumerate(li)
<enumerate object at 0xb717f7ac>
>>> list(enumerate(li))
[(0, 111), (1, 222), (2, 333), (3, 444), (4, 555), (5, 666), (6, 777)]
>>> aa = enumerate(li)
>>> aa
<enumerate object at 0xb71969dc>
>>> for i,j in aa:
...     print('%s,%s'%(i,j))
... 
1,222
2,333
3,444
4,555
5,666
6,777

2、eval:

一、取出字符串中的内容
>>> str2 = '[1,2,3,4]'
>>> li = [11,22,33,44]
>>> str(li)
'[11, 22, 33, 44]'
>>> eval(str2)
[1, 2, 3, 4]
二、将字符串str当成有效的表达式来求指并返回计算结果
>>> sr1 = '3*7'
>>> sr1
'3*7'
>>> eval(sr1)
21

3、exec 执行字符串或complie方法编译过的字符串

>>> str3 = "print('nihao')"
>>> exec(str3)
nihao
>>> a = ("print('True') if 1>0 else print('False')")
>>> exec(a)

4、filter :过滤器       filter(函数,可迭代对象) 以前面函数设定规则进行过滤,对后面可迭代对象进行过滤 ,返回一个对象,通过list和打印   

def func1(n):
    if n > 4:
        return n

li = [11,2,4,56,7,8,9]

aa = filter(func1,li)
print(list(aa))
[11, 56, 7, 8, 9]

5、zip : 将对象逐一配对

li = [1,2,3]
li2 = [4,5,6]
tt = zip(li,li2)
print(list(tt))
[(1, 4), (2, 5), (3, 6)]

6、map: 对于参数iterable中的每个元素都应用fuction函数, 并将结果作为列表返回

以前面函数设定规则进行过滤,对后面可迭代对象进行过滤 ,返回一个对象,通过list和打印   不同点:不符合条件返回‘None’

def func1(n):
    if n > 4:
        return n

li = [11,2,4,56,7,8,9]

bb = map(func1,li)
print(list(bb))
[11, None, None, 56, 7, 8, 9]
原文地址:https://www.cnblogs.com/lyh-520/p/9287199.html