第 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.
多次调用函数
------------------------------------------------------------------------------------------
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')
本文转自 mlwzby 51CTO博客,原文链接:http://blog.51cto.com/aby028/1965495