6.函數基礎和函數參數

             函數基礎            

函數的定義及調用

def func():          #def 函數名(參數):
    pass                      #跳過
func()                  #函數的調用

一、函數的定義

def 函數名(參數):python

  pass函數

函數名命名規則: 字母、數字和下劃線組成,和 變量命名規則一致ui

二、函數的調用

          函數名()spa

            函數參數             

函數參數的定義

一、必備參數

def func(x):
    pass

二、默認參數:

def func(x,y=None)
    pass

三、不定長參數:

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

參數的調用: 一、經過位置傳遞參數(未命名參數) 二、經過關鍵字傳遞參數(命名參數)debug

在python中參數無類型,參數能夠接受任意對象, 只有函數中代碼纔會對參數類型有限制code

函數參數調用演示

 一、必備參數:

在函數調用的時候,必備參數必需要傳入orm

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

二、默認參數:

在函數調用的時候,默認參數能夠不傳入值,不傳入值時,會使用默認參數對象

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

三、不定長參數:

在函數調用的時候,不定長參數能夠不傳入,也能夠傳入任意長度。 其中定義時,元組形式能夠放到參數最前面,字典形式只能放到最後面blog

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中簡單內置函數

一、內置對象查看

>>> 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']

二、常見函數:

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

三、進制轉換函數:

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中簡單內置函數

一、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

二、eval:

1、取出字符串中的內容
>>> str2 = '[1,2,3,4]'
>>> li = [11,22,33,44]
>>> str(li)
'[11, 22, 33, 44]'
>>> eval(str2)
[1, 2, 3, 4]
2、將字符串str當成有效的表達式來求指並返回計算結果
>>> sr1 = '3*7'
>>> sr1
'3*7'
>>> eval(sr1)
21

三、exec 執行字符串或complie方法編譯過的字符串

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

四、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]

五、zip : 將對象逐一配對

li = [1,2,3]
li2 = [4,5,6]
tt = zip(li,li2)
print(list(tt))
[(1, 4), (2, 5), (3, 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]
相關文章
相關標籤/搜索