一、函数
函数是一个表示一定功能的代码块,可以在程序中进行应用,书写的方式:“函数名.()”。
1、定义一个函数
# -*- coding: gb2312 -*-
#随便定义一个hansh8u
def system_out():
print("hello world !")
system_out()
结果:hello world !
#加粗部分即是函数体
2、函数的形参
2.1、定义一个带形参的函数
def greet_user(username):
"""显示简单的问候语"""
print("Hello, " + username.title() + "!")
greet_user('jesse')
结果:Hello, Jesse!
注意:jesse是个实参,username是个形参。
2.2、多个形参的情况,对应多个实参
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('harry', 'hamster')
结果:I have a hamster.
My hamster's name is Harry.
I have a harry.
My hamster's name is hamster.
注意:此情况下,必须注意形参的填入顺序,否则输出的内容会出现与预期不一样的情况
2.3、关键字实参调用方法
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='harry', animal_type='hamster')
结果:I have a hamster.
My hamster's name is Harry.
I have a hamster.
My hamster's name is Harry.
注意:以上两种情况,函数中实参的调用顺序不一样,但并未影响输出结果,所以关键实参的顺序是不会影响结果的输出的。
2.4、形参的默认值设置
编写函数时,可给每个形参指定默认值 。
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.
注:若不想用设置的默认参数,可以用关键实参方式和位置实参方式两种方法,申明实参。
3、返回值函数
函数可以输出一定结果,也可以通过数据处理之后,返回一个值或一组值到代码中去,返回的值,叫做返回值,调用关键字return
3.1、返回简单值
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)
3.2、可选参数返回值函数
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)
3.3返回字典
返回值即是一个字典。
4、传递列表
def print_models(unprinted_designs, completed_models):
"""
模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移到列表completed_models中
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
# 模拟根据设计制作3D打印模型的过程
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)
结果:
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
5、禁止函数修改列表的表示方法
只需要将列表的表示用切片来表示即可,因为这样切片是作为列表的一个副本,在函数操作过程中,实际修改的是副本
不会影响到列表本身的值。切片的表示方法:unprinted_designs[:] 因此上面的print_models(unprinted_designs, completed_models)中,
如果不想修改unprinted_designs列表,可以写成unprinted_designs[:],就可以避免修改列表的问题了。
6、传递任意数量的实参
6.1、基本使用方法
有时候,你预先不知道函数需要接受多少个实参 ,在python中允许函数从调用语句中手机任意数量的实参。
下面的函数只有一个形参*toppings,但不管调用语句提供了多少实参,这个形参都将它们统统收入囊中:
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
注:*toppings让python创建一个空的名字叫做toppings的元组
6.2、接受任意实参的形参必须放置到函数括号的最后
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
注:接纳任意数量实参的形参必须放在,函数括号里面的最后位置上
6.3、使用任意数量的“键—值”对实参
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)
注:形参**user_info中的两个*让Python创建一个名为user_info的空字典
7、函数的模块化储存
7.1、导入函数的整个模块
要让函数是可导入的,得先创建模块。 模块是扩展名为.py的文件,包含要导入到程序中的代码。下面来创建一个包含函数make_pizza()的模块:
首先在编程软件里面创建pizza.py的模块(或者可以称为文件)
然后在pizza.py中写入如下函数:
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
接下来我们创建一个make_pizzas.py的文件,在里面调用两次make_pizza()函数:
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
解释:当python读取代码的时候,读取到import pizza的时候,python就会打开pizza.py文件,并且隐形的将pizza.py中的
所有代码都复制到当前make_pizzas程序中来,当我们要调用pizza.py中的某个函数时,就可以用pizza.make_pizza(实参1,实参2)的形式调用对应函数。
7.2、导入制定的函数
当我们导入整个模块(或者叫做程序文件)的时候,可以用“