Python 3 – 函數(shù)
Python 是面向?qū)ο缶幊陶Z言,所有功能都是通過函數(shù)和類實現(xiàn)。愛掏網(wǎng) - it200.com函數(shù)是任何編程語言中最基本的概念之一。愛掏網(wǎng) - it200.com
Python 提供了強大的函數(shù)功能,包括定義參數(shù)、默認參數(shù)、不定長參數(shù)、匿名函數(shù)和高階函數(shù)等等。愛掏網(wǎng) - it200.com
在 Python 中,使用 def
關(guān)鍵字來定義函數(shù)。愛掏網(wǎng) - it200.com下面是一個簡單的函數(shù)定義并調(diào)用的示例:
def greet(name):
print("Hello, " + name + "!")
greet("World") # Hello, World!
在 Python 中,函數(shù)調(diào)用直接使用函數(shù)名并傳遞所需的參數(shù)。愛掏網(wǎng) - it200.com注意,函數(shù)的參數(shù)由一對圓括號括起來,即使沒有參數(shù)也必須使用圓括號。愛掏網(wǎng) - it200.com
參數(shù)的傳遞方式
Python 中函數(shù)的參數(shù)可以通過不同的方式傳遞:位置參數(shù)、默認參數(shù)、關(guān)鍵字參數(shù)和不定長參數(shù)。愛掏網(wǎng) - it200.com
位置參數(shù)
位置參數(shù)是最常用的參數(shù)傳遞方式,順序很重要,按照定義順序一一傳遞參數(shù)。愛掏網(wǎng) - it200.com下面是一個位置參數(shù)的示例:
def add(a, b):
return a + b
print(add(1, 2)) # 3
默認參數(shù)
默認參數(shù)可以指定參數(shù)的默認值,如果沒有傳遞參數(shù)則使用默認值。愛掏網(wǎng) - it200.com下面是一個默認參數(shù)的示例:
def add(a, b=2):
return a + b
print(add(1)) # 3
關(guān)鍵字參數(shù)
關(guān)鍵字參數(shù)可以使用參數(shù)名來傳遞參數(shù),這種方式不依賴于參數(shù)的位置。愛掏網(wǎng) - it200.com下面是一個關(guān)鍵字參數(shù)的示例:
def add(a, b):
return a + b
print(add(b=2, a=1)) # 3
不定長參數(shù)
不定長參數(shù)可以接受任意個參數(shù),可以是位置參數(shù)、默認參數(shù)和關(guān)鍵字參數(shù)。愛掏網(wǎng) - it200.com下面是一個不定長參數(shù)的示例:
def add(*args):
sum = 0
for i in args:
sum += i
return sum
print(add(1, 2, 3, 4, 5)) # 15
匿名函數(shù)
匿名函數(shù)也叫 lambda 函數(shù),是一個沒有名字的函數(shù)。愛掏網(wǎng) - it200.com它可以接收任意多個參數(shù),并且返回一個結(jié)果。愛掏網(wǎng) - it200.com下面是一個匿名函數(shù)的示例:
square = lambda x: x * x
print(square(2)) # 4
在上面的示例中,我們定義了一個 lambda 函數(shù),它接收一個參數(shù) x
并返回 x * x
的結(jié)果。愛掏網(wǎng) - it200.com
高階函數(shù)
高階函數(shù)是一個函數(shù)接收另一個函數(shù)作為參數(shù)或者返回一個函數(shù)。愛掏網(wǎng) - it200.comPython 中內(nèi)置了許多高階函數(shù),包括 map
、filter
和 reduce
等。愛掏網(wǎng) - it200.com
map 函數(shù)
map
函數(shù)可以對序列中的每個元素應(yīng)用一個函數(shù),然后返回一個新序列。愛掏網(wǎng) - it200.com下面是一個 map
函數(shù)的示例:
def square(x):
return x * x
squares = map(square, [1, 2, 3, 4, 5])
print(list(squares)) # [1, 4, 9, 16, 25]
在上面的示例中,我們使用 map
函數(shù)對 [1, 2, 3, 4, 5]
序列中的每個元素應(yīng)用 square
函數(shù),并返回一個新序列 squares
。愛掏網(wǎng) - it200.com
filter 函數(shù)
filter
函數(shù)可以對序列中的元素應(yīng)用一個函數(shù),用于過濾出符合條件的元素,并返回一個新序列。愛掏網(wǎng) - it200.com下面是一個 filter
函數(shù)的示例: