第 8 章主要練習了各類函數,內容以下編程
定義一個簡單的函數app
向函數傳遞信息iphone
什麼是形參ide
什麼是實參函數
位置參數ui
屢次調用函數spa
關鍵字實參orm
默認值參數ip
返回值 returnci
讓參數編程可選的
返回字典
結合使用函數和 while 循環
傳遞列表
在函數中修改列表
傳遞任意數量的實參
傳遞任意數量的參數並循環打印
結合使用位置參數和任意數量實參
使用任意數量的關鍵字實參
導入整個模塊
導入特定的函數
使用 as 給函數指定別名
使用 as 給模塊指定別名
導入模塊中全部的函數
定義一個簡單的函數
直接調用函數,就能打印
--------------------------
def greet_user():
print("Hello!")
greet_user()
---------------------------
Hello!
向函數傳遞信息
username 只是一個形參
------------------------------------------------------
def greet_user(username):
print("Hello, " + username.title() + "!")
greet_user('zhao')
------------------------------------------------------
Hello, Zhao!
什麼是形參?
以上面的代碼爲例。username 就是形參,它只表明 greet_user 這個函數須要傳遞一個參數
至於它是叫 username 仍是 nameuser 都無所謂
什麼實參?
以上面的代碼爲例。’zhao’ 就是實參,一句話總結就是真正要讓代碼執行的參數
位置實參
函數括號中指定了位置實參的順序
輸入參數必須按照形參提示操做
總之就是位置實參的順序很重要
-------------------------------------------------------------------------------------------
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry')
-------------------------------------------------------------------------------------------
I have a hamster.
My hamster's name is Harry.
屢次調用函數
------------------------------------------------------------------------------------------
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')
------------------------------------------------------------------------------------------
I have a hamster.
My hamster's name is Harry.
I have a dog.
My dog's name is Willie.
關鍵字實參
調用函數的時候,連同形參指定實參,就算是位置錯了也能正常調用
------------------------------------------------------------------------------------------
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='willie', animal_type='dog')
------------------------------------------------------------------------------------------
I have a hamster.
My hamster's name is Harry.
I have a dog.
My dog's name is Willie.
默認值
在設定函數 describe_pet 形參中指定一個參數,調用的時候
能夠不用指定,默認就能調用
------------------------------------------------------------------------------------------
def describe_pet(pet_name, animal_type='dog'):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
------------------------------------------------------------------------------------------
I have a dog.
My dog's name is Willie.
還能夠更簡單的調用
------------------------------------------------------------------------------------------
def describe_pet(pet_name, animal_type='dog'):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('willie')
------------------------------------------------------------------------------------------
I have a dog.
My dog's name is Willie.
返回值
return full_name.title() 將 full_name 的值轉換爲首字母大寫格式
並將結果返回到函數調用行
變量 full_name 的行中兩個 + 中間的單引號中間須要有一個空格
若是沒有空格,打印出來的效果也是兩個
-----------------------------------------------------------------
def get_formatted_name(first_name, last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
-----------------------------------------------------------------
Jimi Hendrix
讓參數變成可選的
Python將非空字符串解讀爲 True,若是沒有 middle_name 參數,執行 else 代碼
必須確保 middle_name 參數是最後一個實參
-----------------------------------------------------------------------------------------
def get_formatted_name(first_name, last_name, middle_name=''):
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
-----------------------------------------------------------------------------------------
Jimi Hendrix
John Lee Hooker
返回字典
----------------------------------------------------------------
def build_person(first_name, last_name):
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
----------------------------------------------------------------
{'first': 'jimi', 'last': 'hendrix'}
以上面的代碼爲例,增長一個形參 age,並將其設置爲空字符串
若是用戶輸入了姓名,就將其添加到字典中
-----------------------------------------------------------------
def build_person(first_name, last_name, age=''):
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix', age=18)
print(musician)
-----------------------------------------------------------------
{'first': 'jimi', 'last': 'hendrix', 'age': 18}
結合使用函數和 while 循環
若是用戶輸入 q,能夠隨時退出
----------------------------------------------------------------------------------
def get_formatted_name(first_name, last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name, l_name)
print("\nHello, " + formatted_name + "!")
----------------------------------------------------------------------------------
Please tell me your name:
(enter 'q' at any time to quit)
First name: zhao
Last name: lulu
Hello, Zhao Lulu!
Please tell me your name:
(enter 'q' at any time to quit)
First name: q
傳遞列表
函數中的 greet_users( ) names 參數只是一個形參,
而實參則是要傳入的列表
----------------------------------------------------
def greet_users(names):
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
----------------------------------------------------
Hello, Hannah!
Hello, Ty!
Hello, Margot!
在函數中修改列表
-------------------------------------------------------------------------------------------
unprinted_models = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
while unprinted_models:
current_design = unprinted_models.pop()
print("Printing model: " + current_design)
completed_models.append(current_design)
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
-------------------------------------------------------------------------------------------
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
dodecahedron
robot pendant
iphone case
從新組織以上代碼,用函數的方式調用
-------------------------------------------------------------------------------------------
def print_models(unprinted_designs, completed_models):
while unprinted_designs:
current_design = unprinted_designs.pop()
print("Printing model: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
-------------------------------------------------------------------------------------------
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
dodecahedron
robot pendant
iphone case
傳遞任意數量的實參
-----------------------------------------------------------------------------
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
-----------------------------------------------------------------------------
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
傳遞任意數量的參數並循環打印
----------------------------------------------------------------------------
def make_pizza(*toppings):
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
----------------------------------------------------------------------------
Making a pizza with the following toppings:
- pepperoni
Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
結合使用位置參數和任意數量實參
-----------------------------------------------------------------------------------------------------
def make_pizza(size, *toppings):
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(17, 'pepperoni')
make_pizza(19, 'mushrooms', 'green peppers', 'extra cheese')
-----------------------------------------------------------------------------------------------------
Making a 17-inch pizza with the following toppings:
- pepperoni
Making a 19-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
使用任意數量的關鍵字實參
先定義一個空列表
for 循環中將參數添加到 profile 字典中,並用 return 返回
---------------------------------------------------------------
def build_profile(first, last, **user_info):
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
---------------------------------------------------------------
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
導入整個模塊
pizza.py 文件內容以下
------------------------------------------------------------------------------------------------------
def make_pizza(size, *toppings):
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
making_pizzas.py 文件內容以下
----------------------------------------------------------------------------------------
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
----------------------------------------------------------------------------------------
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
導入特定的函數
---------------------------------------------------------------------------------
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
---------------------------------------------------------------------------------
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
使用 as 給函數指定別名
--------------------------------------------------------------------
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
使用 as 給模塊指定別名
------------------------------------------------------------------------------------
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
導入模塊中全部的函數
-----------------------------------------------------------------------------------
from pizza import *
make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')