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')
>>> 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'
返回一個對象,用變量去接收,轉換成列表,元素值和下標一一對應取出,可經過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
>>> str2 = '[1,2,3,4]' >>> li = [11,22,33,44] >>> str(li) '[11, 22, 33, 44]' >>> eval(str2) [1, 2, 3, 4]
>>> sr1 = '3*7' >>> sr1 '3*7' >>> eval(sr1) 21
>>> str3 = "print('nihao')" >>> exec(str3) nihao >>> a = ("print('True') if 1>0 else print('False')") >>> exec(a)
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]
li = [1,2,3] li2 = [4,5,6] tt = zip(li,li2) print(list(tt)) [(1, 4), (2, 5), (3, 6)]
之前面函數設定規則進行過濾,對後面可迭代對象進行過濾 ,返回一個對象,經過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]