第 8 章主要練習了各種函數,内容如下
定義一個簡單的函數
向函數傳遞資訊
什麼是形參
什麼是實參
位置參數
多次調用函數
關鍵字實參
預設值參數
傳回值 return
讓參數程式設計可選的
傳回字典
結合使用函數和 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.
------------------------------------------------------------------------------------------
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')
I have a dog.
My dog's name is Willie.
調用函數的時候,連同形參指定實參,就算是位置錯了也能正常調用
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='willie', animal_type='dog')
預設值
在設定函數 describe_pet 形參中指定一個參數,調用的時候
可以不用指定,預設就能調用
def describe_pet(pet_name, animal_type='dog'):
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
還可以更簡單的調用
describe_pet('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('john', 'hooker', 'lee')
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')
{'first': 'jimi', 'last': 'hendrix'}
以上面的代碼為例,增加一個形參 age,并将其設定為空字元串
如果使用者輸入了姓名,就将其添加到字典中
-----------------------------------------------------------------
def build_person(first_name, last_name, age=''):
if age:
person['age'] = age
musician = build_person('jimi', 'hendrix', age=18)
{'first': 'jimi', 'last': 'hendrix', 'age': 18}
如果使用者輸入 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!
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']
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
-----------------------------------------------------------------------------
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
----------------------------------------------------------------------------
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
Making a pizza with the following toppings:
- pepperoni
- 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:
make_pizza(17, 'pepperoni')
make_pizza(19, 'mushrooms', 'green peppers', 'extra cheese')
Making a 17-inch pizza with the following toppings:
Making a 19-inch pizza with the following toppings:
先定義一個空清單
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 檔案内容如下
------------------------------------------------------------------------------------------------------
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:
Making a 12-inch pizza with the following toppings:
---------------------------------------------------------------------------------
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
- extra cheese
--------------------------------------------------------------------
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
------------------------------------------------------------------------------------
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
-----------------------------------------------------------------------------------
from pizza import *
本文轉自 mlwzby 51CTO部落格,原文連結:http://blog.51cto.com/aby028/1965495