1.定义函数
#helloword.py
def greet_user():
print("Hello!")
greet_user()
输出为:
D:\www>python helloword.py
Hello!
2、向函数传递信息
1)位置实参
#helloword.py
def greet_user(username):
print("Hello,"+username+"!")
username=input("please input your name")
greet_user(username)
输出为:
D:\www>python helloword.py
please input your namejin
Hello,jin!
2)关键字实参
#helloword.py
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(pet_name="miaomiao",animal_type="cat")
输出为:
D:\www>python helloword.py
I have a cat.
My cat's name is Miaomiao.
关键字实参是传递给函数的名称-值对。
使用关键字实参时,务必准确地指定函数定义中的形参名。
3)默认值
#helloword.py
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("miaomiao")
输出:
D:\www>python helloword.py
I have a dog.
My dog's name is Miaomiao.
3.返回值
1)返回简单值
#helloword.py
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)
输出为:
D:\www>python helloword.py
Jimi Hendrix
2)返回字典
函数可以返回任何类型的值,包括列表和字典等较复杂的数据结构
#helloword.py
def get_formatted_name(first_name,last_name):
person={'first':first_name,'last':last_name}
return person
musician=get_formatted_name('jimi','hendrix')
print(musician)
输出为:
D:\www>python helloword.py
{'first': 'jimi', 'last': 'hendrix'}
4、传递列表
1)在函数中修改列表
#helloword.py
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):
print("\nThe following models have been printed:")
for model in completed_models:
print(model)
a=['iphone','robot','dodecahedron']
b=[]
print_models(a,b)
show(b)
输出为:
D:\www>python helloword.py
Printing model: dodecahedron
Printing model: robot
Printing model: iphone
The following models have been printed:
dodecahedron
robot
iphone
2)禁止函数修改列表
可向函数传递列表的副本而不是原件,这样函数所做的任何修改都只影响副本,而丝毫不影响原件。
要将列表的副本传递给函数,可以像下边这样做:
fuction_name(list_name[:])
切片表示法[:]创建列表的副本。
让函数使用现成列表可避免花时间和内存创建副本,从而提高效率,在处理大型列表时尤其如此。
5、传递任意数量的实参
1)下面函数只有一个形参*toppings,但不管调用语句提供多少实参,这个形参都将将他们统统收入囊中。
#helloword.py
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('egg','apple','cheese')
输出为:
D:\www>python helloword.py
('pepperoni',)
('egg', 'apple', 'cheese')
形参名*toppings中的星号让python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。
2)有时候需要接受任意数量实参,但是预先不知道传递给函数的会是什么样的信息。这种情况下,可将函数编写成能够接受任意数量的键值对——调用语句提供了多少就接受多少。
#helloword.py
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','einstrin',location='princeton',field='physics')
print(user_profile)
输出为:
D:\www>python helloword.py
{'first_name': 'albert', 'last_name': 'einstrin', 'location': 'princeton', 'field': 'physics'}
形参**user_profile中的两个星号让python创建一个名为profile的空字典,并将收到的所有名称-值对都封装在这个字典中。在这个函数中,可以像访问其他字典那样访问user_info中的名称—值对。
6、将函数存储在模块中
1)导入整个模块
要让函数是可导入的,得先创建模块。模块是扩展名为.py的文件,包含要导入到程序中的代码。
# pizza.py
def make_pizza(size,*toppings):
print("\nMaking a "+str(size)+"-inch pizza with the follwing toppings:")
for topping in toppings:
print("-"+topping)
# making_pizzas.py
import pizza
pizza.make_pizza(16,'egg')
pizza.make_pizza(12,'mushroom','peppers','cheese')
输出为:
D:\www>python making_pizzas.py
Making a 16-inch pizza with the follwing toppings:
-egg
Making a 12-inch pizza with the follwing toppings:
-mushroom
-peppers
-cheese
只需编写一条import语句并在其中指定模块名,就可在程序中使用该模块中的所有函数。
2)导入特定的函数
# making_pizzas.py
from pizza import make_pizza
make_pizza(16,'egg')
make_pizza(12,'mushroom','peppers','cheese')
输出为:
D:\www>python making_pizzas.py
Making a 16-inch pizza with the follwing toppings:
-egg
Making a 12-inch pizza with the follwing toppings:
-mushroom
-peppers
-cheese
若使用这种语法,调用函数时就无需使用句点。
3)使用as给函数指定别名
# making_pizzas.py
from pizza import make_pizza as mp
mp(16,'egg')
mp(12,'mushroom','peppers','cheese')
输出为:
D:\www>python making_pizzas.py
Making a 16-inch pizza with the follwing toppings:
-egg
Making a 12-inch pizza with the follwing toppings:
-mushroom
-peppers
-cheese
4)使用as给模块指定别名
# making_pizzas.py
import pizza as p
p.make_pizza(16,'egg')
p.make_pizza(12,'mushroom','peppers','cheese')
输出为:
D:\www>python making_pizzas.py
Making a 16-inch pizza with the follwing toppings:
-egg
Making a 12-inch pizza with the follwing toppings:
-mushroom
-peppers
-cheese
5)导入模块中的所有函数
# making_pizzas.py
from pizza import *
make_pizza(16,'egg')
make_pizza(12,'mushroom','peppers','cheese')
输出为:
D:\www>python making_pizzas.py
Making a 16-inch pizza with the follwing toppings:
-egg
Making a 12-inch pizza with the follwing toppings:
-mushroom
-peppers
-cheese
由于导入了每个函数,可通过名称来调用每个函数,而无需使用句点表示法。