作者:PyQuant
博客:https://blog.csdn.net/qq_33499889
慕課:https://mooc1-2.chaoxing.com/course/207443619.html
點贊、關注再看,養成良好習慣
Life is short, U need Python
初學Python,快來點我吧
1. 函數的基本結構
2. 函數的定義
def hello():
print('hello python!')
hello()
hello python!
def foo(a,b):
c = a + b
return c
r = foo(10,20)
print(r)
30
3. 函數的參數
函數的參數類型一般分爲如下四種形式:
-
必需參數
-
關鍵字參數
-
默認參數
-
不定長參數
【1】必須參數
-
必需參數須以正確的順序傳入函數。
-
調用時的數量必須和聲明時的一樣,不然會出現語法錯誤。
-
實例:
def myprint(my_string):
print(my_string)
myprint('hello python')
hello python
【2】關鍵字參數
-
關鍵字參數和函數調用關係緊密,函數調用使用關鍵字參數來確定傳入的參數值。
-
使用關鍵字參數允許函數調用時參數的順序與聲明時不一致,因爲 Python 解釋器能夠用參數名匹配參數值。
-
實例:
def print_me(name, age):
print ("名字: ", name)
print ("年齡: ", age)
return
print_me("PyQuant", 30 )
名字: PyQuant
年齡: 30
print_me(age=30, name="PyQuant" )
名字: PyQuant
年齡: 30
【3】默認參數
-
調用函數時,如果沒有傳遞參數,則會使用默認參數。以下實例中如果沒有傳入 age 參數,則使用默認值。
-
實例:
def print_me(name, age=30):
print ("姓名-->", name)
print ("年齡-->", age)
return
print_me("PyQuant" )
姓名--> PyQuant
年齡--> 30
print_me("PyQuant" ,40)
姓名--> PyQuant
年齡--> 40
【4】不定長參數
- 你可能需要一個函數能處理比當初聲明時更多的參數。這些參數叫做不定長參數,和上述參數不同,聲明時不會命名。
- 實例
def print_me(arg, *args):
print('arg -->', arg)
print('*args -->', args)
print_me(30,2,3,4)
arg --> 30
*args --> (2, 3, 4)
def print_me(arg, **args):
print('arg -->', arg)
print('**args -->', args)
print_me(30,a=2,b=3,c=4)
arg --> 30
**args --> {'a': 2, 'b': 3, 'c': 4}
4. 特殊函數
-
lambda函數
-
map()函數
-
filter()函數
【1】lambda
Python 使用 lambda 來創建匿名函數,不再使用 def 語句這樣標準的形式定義一個函數。
-
lambda 只是一個表達式,函數體比 def 簡單很多。
-
lambda的主體是一個表達式,而不是一個代碼塊。僅僅能在lambda表達式中封裝有限的邏輯進去。
-
lambda 函數擁有自己的命名空間,且不能訪問自己參數列表之外或全局命名空間裏的參數。
polynomial = lambda x,y: x**2 + y**2
polynomial(1,2)
5
【2】map()
map() 函數會根據提供的函數對指定序列做映射。
其語法形式爲:map(function, iterable, …):
-
function ---- 以參數序列中的每一個元素調用 function 函數。
-
iterable ---- 一個或多個序列(比如:列表、元組和字典等)。
-
返回值 ---- Python 3.x 返回迭代器,通過序列的內置函數(比如: list,tuple,set等)進行顯示。
lst = [1,2,3]
m = map(lambda x: 10*x ,lst)
m
<map at 0x1c93abb7208>
list(m)
[10, 20, 30]
def f(x,y):
return (x,y)
lst_1 = [0,1,2,3,4,5,6]
lst_2 = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
print(list(map(f,lst_1,lst_2)))
[(0, 'Sun'), (1, 'Mon'), (2, 'Tue'), (3, 'Wed'), (4, 'Thu'), (5, 'Fri'), (6, 'Sat')]
【3】filter()
filter() 函數用於過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的新列表。
其語法形式爲:filter(function, iterable)
-
function ---- 判斷函數。
-
iterable ---- 可迭代對象。
-
返回值 ---- Python 3.x 返回迭代器。
numbers = range(-3,3)
f = filter(lambda x: x > 0, numbers)
f
<filter at 0x1c93ab05b70>
list(f)
[1, 2]
5. 作用域
-
局部作用域(Local)
-
全局作用域(Global)
-
嵌套作用域(Enclosing)
-
內置作用域(builtin)
【1】局部作用域(Local)
a = 100
def func():
a = 300
print('局部作用域: ', a)
func()
局部作用域: 300
【2】全局作用域(Global)
a = 100
def func():
a = 300
print('局部作用域: ', a)
func()
print('全局作用域: ', a)
局部作用域: 300
全局作用域: 100
a = 100
def func():
a += 100
print('局部作用域: ', a)
func()
print('全局作用域: ', a)
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-41-4c68dbc3afd0> in <module>()
3 a += 100
4 print('局部作用域: ', a)
----> 5 func()
6 print('全局作用域: ', a)
<ipython-input-41-4c68dbc3afd0> in func()
1 a = 100
2 def func():
----> 3 a += 100
4 print('局部作用域: ', a)
5 func()
UnboundLocalError: local variable 'a' referenced before assignment
a = 100
def func():
global a
a += 100
print('局部作用域: ', a)
func()
print('全局作用域: ', a)
局部作用域: 200
全局作用域: 200
【3】嵌套作用域(Enclosing)----> 嵌套函數
x = 123
def f1():
x = 100
print('f1--->',x)
def f2():
x = 200
print('f2--->',x)
f2()
f1()
f1---> 100
f2---> 200
【4】內置作用域(builtin)
import builtins
print(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', '__IPYTHON__', '__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', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'get_ipython', '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', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
- 寫作不易,切勿白剽
- 博友們的點贊和關注就是對博主堅持寫作的最大鼓勵
- 持續更新,未完待續…