1.系統(tǒng)自帶的函數(shù):
>>> 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', 'ModuleNotFoundError', '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', 'WindowsError', '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.定義一個函數(shù)
>>> def a2_333():???????????? #def定義一個函數(shù),a2_333函數(shù)名,字母開頭
...???? pass???????????????? ?#()中的參數(shù)可有可無
...
?
>>> a2_333????????????????? #未調(diào)用函數(shù),只是打印了一下函數(shù)名
<function a2_333 at 0x0000019CF2431EA0>???? ?#function代表該名字是函數(shù)
??????????????????????????????????????????? #at代表了該函數(shù)在內(nèi)存中的地址
>>> a2_333()???????????????? #函數(shù)名后加(),便可調(diào)用該函數(shù)
>>>?
?
>>> def count_letter(s):??????? #函數(shù)名不要與系統(tǒng)自帶的函數(shù)名、定義的變量名沖突,
...???? result=0?????????????? #s為參數(shù),在括號中可以寫多個參數(shù),無限制
...???? for i in s:
...???????? if i >="a" and i <="z":
...???????????? result=result 1
...???? return result??????????? #函數(shù)執(zhí)行完畢后,一定要有個返回值
...
>>> count_letter("a1b2Z3")
2
?
>>> count_letter("skdjhf3ksdhf")?? #函數(shù)定義好后,傳不同的參數(shù),均能正確輸出
11??????????????????????????? ?#封裝的概念,調(diào)用時不用關(guān)注內(nèi)部的邏輯
?
>>>count_letter()??????????????? #調(diào)用的時候,傳參一個都不能少,除非函數(shù)使用默認
Traceback (most recent call last):?? ?#參數(shù)
? File "<stdin>", line 1, in <module>
TypeError: count_letter() missing 1 required positional argument: 's'
?
>>> def count_digit(s):
...???? result=0
...???? for i in s:
...???????? if i>="0" and i<="9":
...???????????? result =1
...?????????????????????????? ?????????#該函數(shù)就沒有返回值
...
>>> print(count_digit("sadhfasjdgsjf"))???? #沒有return的函數(shù),默認返回None
None
>>> print(count_digit("ssjhd24")) ????????#沒有return的函數(shù),默認返回None
None
?
>>> def count_digit(s):
...???? result=0
...???? for i in s:
...???????? if i>="0" and i<="9":
...???????????? result =1
...???? return???????????????????????? #有return,但是后面沒有寫任何參數(shù)??
...
>>> print(count_digit("sadhfasjdgsjf"))? ?#依然返回None
None
>>> print(count_digit("ssjhd24"))
None
?
>>> print(None)?????????????????????? #單獨打印None,還是會有結(jié)果輸出
None
?
>>> print(none)????????????????????? ?#打印小寫none,提示未定義
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
NameError: name 'none' is not defined
?
?
3.函數(shù)的建壯性
輸入兩個數(shù),返回相加的結(jié)果:
def add(a,b):
??? return(a b)
?
print(add(1,2)) ?????????????#在文件中執(zhí)行時,一定要加print,否則無輸出結(jié)果
?
>>> add(1,2)?????????????? #終端模式時,不必加print便有正確輸出
3
該代碼存在安全隱患,如果a,b類型不一致,會報錯
>>> def add(a,b):
...???? return(a b)
...
>>> add(1,"2")???????????? #傳入的a,b的類型不一致
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
? File "<stdin>", line 2, in add
TypeError: unsupported operand type(s) for : 'int' and 'str'
?
改進后的代碼是:
def add(a,b):
? ??if isinstance(a,(int,float,complex)) and isinstance(b,(int,float,complex)): #判斷a,b是否都
??????? return(a b)???????????????????????????????????????????? #是int類型
??? print("Adding different types of objects is not supported")????? ?#return具有短路功能
??? return None
print(add(1,"2"))
執(zhí)行結(jié)果:
E:\>python a.py
Adding different types of objects is not supported
None
?
?
4.函數(shù)的作用域
>>> n=1??????????????????? #全局變量
>>> def func():
...???? n=2????????????????? #在函數(shù)內(nèi)部定義的變量叫做局部變量,函數(shù)體內(nèi)部有效
...???? return n
...
>>> print(func())??????????? ?#返回函數(shù)內(nèi)的n值
2
>>> print(n)???????????????? #返回全局變量n的值
1
?
?
>>> def func():
...???? n=2?????????????????? #只存在一個局部變量n,不存在全局變量n
...???? return n
...
>>> print(func())
2
>>> print(n)????????????????? #不存在全局變量n,提示n未定義
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
?
?
n=1????????????????????????? #全局變量中有n
def func():
??? return n 1??????????????? #函數(shù)中使用了n,但是在函數(shù)中未定義,會現(xiàn)在函數(shù)體內(nèi)
??????????????????????????? #部找n,如果找不到,就到函數(shù)外面找
print(func())
運行結(jié)果:
E:\>python a.py
2??????????????????????????? ?#依然能返回正確的結(jié)果
?
?
n=1???????????????????????? ?#n是全局變量
def func():
??? n =1???????????????????? #n在函數(shù)中還未賦值,就加1
??? return n
print(func())
print(n)
運行結(jié)果:
E:\>python a.py
Traceback (most recent call last):
? File "a.py", line 6, in <module>
??? print(func())
? File "a.py", line 3, in func
??? n =1
UnboundLocalError: local variable 'n' referenced before assignment
局部變量n在賦值前被引用了,意思就是還未賦值
?
解決方法:在函數(shù)內(nèi)部也先賦一下值
n=1
def func():
??? n=10
??? n =1
??? return n
print(func())
print(n)
運行結(jié)果:
E:\>python a.py
11
1
?
解決方法:使用全局變量的n
n=1
def func():
??? global n????????????? #函數(shù)內(nèi)部,也使用全局變量的n
??? n =1??????????????? #函數(shù)內(nèi)部n 1,同時全局變量的n也加了1
??? return n
print(func())
print(n)
運行結(jié)果:
E:\>python a.py????????? ?#n為2
2?????????????????????? #此方法不推薦
2
?
n=1
def func(a):
??? a =1
??? return a
print(func(n))???????????? #傳的參數(shù)為n,n在程序中是全局變量1,所以a=2
print(n)????????????????? #此方法比較推薦使用
運行結(jié)果:
E:\>python a.py
2
1
?
?
n=[]??????????????????? ?#n在全局變量的位置,但是是列表,列表是可變對象
def func(a):
??? a.append(1)
??? return a
print(func(n))
print(n)
運行結(jié)果:
E:\>python a.py
[1]
[1]
?
?
n={}
def func(a):
??? a[1]=1
??? return a
print(func(n))
print(n)
運行結(jié)果;
E:\>python a.py
{1: 1}
{1: 1}
?
?
n="abc"
def func(a):
??? a=a "d"
??? return a
print(func(n))
print(n)
運行結(jié)果:
E:\>python a.py
abcd
abc
原則1:
如果你傳入的參數(shù)是變量a,這個變量是可變類型(list,dict,set)
那么函數(shù)內(nèi)部對于這個參數(shù)的所有操作結(jié)果都會影響外部的參數(shù)值
原則2:
如果你傳入的參數(shù)是個變量a,這個變量是不可變類型(字符串,整數(shù),小數(shù),元祖)
那么函數(shù)內(nèi)部對于這個參數(shù)的所有操作結(jié)果都不會影響外部的參數(shù)值
?
?
>>> def func():
...???? n=2
...???? return n
...
>>> func=1???????????????? #func是一個函數(shù)的名字,賦值后,從函數(shù)變成了int
>>> func()????????????????? #整數(shù)加(),打印時提示不可調(diào)用
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
?
>>> del func??????????????? #非內(nèi)置的函數(shù),提示不可調(diào)用后,可刪除后再次定義
>>> def func():
...???? n=2
...???? return n
...
>>> print(func())???????????? #函數(shù)功能正常
2
?
?
>>> del func()?????????????? #當刪除函數(shù)時,不要加(),否則會報錯兒
? File "<stdin>", line 1
SyntaxError: can't delete function call
?
?
>>> print(len("abc"))????????? #len函數(shù)是系統(tǒng)自帶的函數(shù)
3
>>> len=10??????????
>>> print(len)????????????? ?#len變成了10
10
>>> print(len("abc"))???????? #此時在調(diào)用函數(shù),提示int類型不可調(diào)用
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del len?????????????????? #刪除掉len
>>> print(len("abc"))?????????? #len為系統(tǒng)自帶函數(shù),刪除后未經(jīng)再次定義依然可以調(diào)用
3
?
?
5.調(diào)用時參數(shù)
1)?????? 必填參數(shù)
>>> def add(a,b):??????????? ?#函數(shù)定義了兩個參數(shù)a,b
...???? return(a b)
...
>>> print(add(1))???????????? #調(diào)用時只傳入了一個參數(shù)
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
TypeError: add() missing 1 required positional argument: 'b'?????? #報錯,少參數(shù)
?
2)?????? 可選參數(shù)
>>> def add(a,b=100):??????? #定義了兩個參數(shù)a,b,b的默認值是100
...???? return(a b)
...
>>> print(add(1))???????????? #雖然只傳入了一個參數(shù),但是能正確輸出結(jié)果,原因在于
101??????????????????????? ?#b使用的是默認參數(shù)值
默認值是在定義時就設(shè)定的。
?
?
>>> def add(a,b=100):??????? #參數(shù)b的默認值是100
...???? return(a b)
...
>>> print(add(1,10))???????? #傳入的b值是10
11??????????????????????? ?#最后打印使用的是傳入的值,非默認值
?
?
>>> def add(a,b=100):
...???? return(a b)
...
>>> print(add(b=1,a=10))?? #調(diào)用時,參數(shù)賦值,也可正確輸出
11
?
?
>>> def add(a,b=100):?????? #a是必填參數(shù),b是可選參數(shù)
...???? return a b
...
>>> print(add(b=1))???????? #傳參時,必填參數(shù)無,會報錯
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
TypeError: add() missing 1 required positional argument: 'a'
?
?
>>> def add(a=100,b):?????? #默認值參數(shù)后有非默認值參數(shù)
...???? return a b??????????
...
? File "<stdin>", line 1
SyntaxError: non-default argument follows default argument
默認值參數(shù)后面跟了非默認值參數(shù)
函數(shù)定義時,默認值參數(shù)的后面不能有非默認值參數(shù),
?
3)?????? 可變參數(shù):
def add(a,b,*c):
??? print(type(c))
??? print(c)?????????????????????? ?#可變參數(shù)不需要對應(yīng),便可正確輸出
??? return a,b,c
print(add(1,2,3,4,5))
運行結(jié)果:
E:\>python a.py
<class 'tuple'>??????????????????? ?#c的類型是元祖
(3, 4, 5)????????????????????????? ?#c的值是(3,4,5)
(1, 2, (3, 4, 5))????????????????????? #a的值是1,b的值是2
?
?
def add(a,b,**c):??????????????? #c前面有兩個*
??? print(type(c))
??? print(c)
?
print(add(1,2,c=3,d=4,e=5))
運行結(jié)果:
E:\>python a.py
<class 'dict'>????????????????? #c的類型是dict
{'c': 3, 'd': 4, 'e': 5}???????????? ?#c的值是賦值的結(jié)果,c,d,e是key,3,4,5,是value
None
?
?
>>> def add(a,b,*c):
...???? print(type(c))
...???? print(c)
...???? return a,b,c
...
>>> print(add(1,2,3,4,5))
<class 'tuple'>
(3, 4, 5)
(1, 2, (3, 4, 5))
>>> print(a)??????????????????????????? #a為非可變參數(shù),未對應(yīng)賦值,便提示未定義
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
?
?
def add(a,b,*c):
??? print(type(c))
??? print(c)
??? return a,b,c
a,b,*c=add(1,2,3,4,5)??????????????????? #a,b非可變參數(shù)賦值后,可正常打印
print(add(1,2,3,4,5))
print(a)
print(b)
運行結(jié)果:
E:\>python a.py
<class 'tuple'>
(3, 4, 5)
<class 'tuple'>
(3, 4, 5)
(1, 2, (3, 4, 5))
1
2
?
?
6.返回時多個參數(shù)
def time_ten_bigger(a,b):
??? return a*10,b*10
print(time_ten_bigger(1,10))??
print(a)
print(b)??????
運行結(jié)果:
E:\>python a.py
(10, 100)?????????????????????? #返回了函數(shù)調(diào)用的結(jié)果
Traceback (most recent call last):
? File "a.py", line 5, in <module>
??? print(a)
NameError: name 'a' is not defined#print(a)提示a未定義
?
正確的代碼是:
def time_ten_bigger(a,b):
??? return a*10,b*10????????? ?#返回兩個值,實際自動的將兩個值放在了元祖里
a,b=time_ten_bigger(1,10)?????? #將a,b分別與函數(shù)的參數(shù)對應(yīng)
print(time_ten_bigger(1,10))??
print(a)
print(b)
運行結(jié)果:
E:\>python a.py
(10, 100)?????????????????????? #函數(shù)返回的值
10??????????????????????????? ?#a的值
100??????????????????????????? #b的值
?
def time_ten_bigger(a,b):?????????
??? return a*10,b*10???????????? #函數(shù)返回值參數(shù)都乘以10
a,b=time_ten_bigger(1,10)???????? #a是1的十倍,b是10的十倍
print(time_ten_bigger(b=1,a=10))?? #這個函數(shù)定義的參數(shù)前后位置不一樣
print(a)
print(b)????
運行結(jié)果:
E:\>python a.py
(100, 10)
10
100???
?
小練習:
1.統(tǒng)計一句話中有多少個數(shù)字
>>> def count_digit(s):
...???? result=0
...???? for i in s:
...???????? if i>="0" and i<="9":
...???????????? result =1
...???? return result??????????????
...
>>> count_digit("sadhfasjdgsjf")
0
>>> count_digit("ssjhd24")
2
?
?
2.使用可變參數(shù)的方式求1-5的和
def add(a,b,*c):????????????????? #c是個元祖,使用遍歷的方法
??? result=0
??? for i in c:
??????? result =i
??? return result a b
print(add(1,2,3,4,5))
運行結(jié)果:
E:\>python a.py
15
?
?
3.使用可變參數(shù),求add(1,2,c=3,d=4,e=5)所有數(shù)的和
def add(a,b,**c):???????????????? ?#c是字典,遍歷字典的values值
??? result=0???????????????????? #方法1:
??? for i in c.values():?????????????????
??????? result =i
??? return a b result
print(add(1,2,c=3,d=4,e=5))
運行結(jié)果:
E:\>python a.py
15
?
def add(*a,**c):??????????????? #方法2:字典 元祖
??? result=0?
? ??for i in a:
??????? result =i??????????
??? for i in c.values():?????????????????
??????? result =i
??? return result
print(add(1,2,c=3,d=4,e=5))
運行結(jié)果:
E:\>python a.py
15
?
?
4.使用可變參數(shù),求add(1,2,3,4,c=5,d=6,e=7)的和
def add(a,b,*c,**d):
??? result=a b
??? for i in d.values():
??????? result =i
??? for i in c:
??????? result =i
??? return result
print(add(1,2,3,4,c=5,d=6,e=7))
運行結(jié)果:
E:\>python a.py
28
?
來源:http://www.icode9.com/content-1-112451.html