python筆記 009 函式(上)

2021-08-03 04:19:26 字數 2234 閱讀 9665

# ★迭代是python最強大的功能之一,是訪問集合元素的一種方式

# ★迭代器是乙個可以記住遍歷的位置的物件

# ★迭代器物件從集合的第乙個元素開始訪問,直到所有的元素被訪問完結束。迭代器只能往前不會後退

# ★迭代器有兩個基本的方法:iter()和 next()

# ★字串,列表或元組物件都可用於建立迭代器

numbers = [1, 2, 3, 4, 5]

num_it = iter(numbers)

print(next(num_it)) # 1

print(next(num_it)) # 2

# ★使用for遍歷迭代器

print('*****=')

for x in num_it:

print (str(x))

print('*****=')

# 函式

# 定義乙個函式def 函式名()

def add(a, b):

"""輸出a+b的和"""

print(str(a + b))

# 呼叫函式

add(3, 2)

# 關鍵字實參

def show_pet(pet_type, pet_name):

"""顯示寵物資訊"""

print("pet_type: " + pet_type)

print("pet_name: " + pet_name)

# 在呼叫的時候指定實參對應的形參,可不按順序

show_pet(pet_name='tony', pet_type='dog')

# 預設值

def show_pet2(pet_name, pet_type='dog'):

"""顯示寵物資訊"""

print("pet_type: " + pet_type)

print("pet_name: " + pet_name)

show_pet2(pet_name='zzz')

''' 由於給pet_type指定了預設值,無需通過實參來指定動物型別,

因此 在函式呼叫中只包含乙個實參——寵物的名字。然而,python

依然將這個實參視為位置實參,因此如果函式呼叫中只包含寵物的名字,

這個實參將關聯到函式定義中的第乙個形參。這就是需要將pet_name

放在形參列表開頭的原因所在

'''# 返回值

def getfullname(first_name, last_name):

full_name = first_name + ' ' + last_name

return full_name.title()

print(getfullname('san', 'zhang'))

# ★不修改原列表的方法

# ★可傳入乙個副本進行操作

# ★例如print_models(unprinted_designs[:], completed_models)

# ★傳入unprinted_designs[:]為副本

# ★傳遞任意數量的引數

def make_pizza(*toppings):

"""列印顧客點的所有配料"""

print(toppings)

make_pizza('pepperoni')

make_pizza('mushrooms', 'green peppers', 'extra cheese')

# 結果:

''' ('pepperoni',)

('mushrooms', 'green peppers', 'extra cheese')

'''# 函式建立乙個空元組進行接受實參

# 結合使用位置實參和任意數量實參

def make_pizza2(size, *toppings):

"""概述要製作的比薩"""

print("\n****** a " + str(size) +

"-inch pizza with the following toppings:")

for topping in toppings:

print("- " + topping)

make_pizza2(16, 'pepperoni')

make_pizza2(12, 'mushrooms', 'green peppers', 'extra cheese')

# 必須在函式定義中將接納任意數量實參的形參放在最後

Python 迴圈和函式(上)

1 真正的用途是用於可迭代物件 1 列表 a 1,2,3,4,5,1,2,3 aduh 2 元組 a 1,2,3,1,2,3 aduh 3 字典 a 4 集合 a 2 計數功能 range從0開始步長預設1 for i in range 10 print i range產生不變的數值串行 1 ran...

(補篇)python函式(上)

這個 符號是交集運算 s1 s2 result s1 s2 輸出結果是 這個 符號是並集運算 result s1 s2 輸出 這個 符號是差集運算 result s1 s2 輸出 result s2 s1 輸出 這個 符號是亦或集 result s1 s2 輸出 檢查乙個集合是否是另乙個集合的子集 ...

python 基礎 4 2 高階函式上

一.高階函式 把函式當做引數傳遞的一種函式 1 map 函式 map函式是python內建的乙個高階函式,它接受乙個函式f和乙個list,並把list元素以此傳遞給函式f,然後返回乙個函式f處理完所有list元素的列表,如下所示 map 函式,傳入的必須是乙個可迭代的物件 lt 1,2,3,4,5 ...