#定义函数格式,比如:
def greet_user():
print("Hello!")
greet_user()
#向函数传递信息,比如:
def greet_user(username):
print("Hello, "+username.title())
greet_user("rose")
#实参和形参。形参是函数完成其工作所需的一项信息。实参是调用函数时传递给函数的信息。以上例子中username是形参,rose是实参。
#位置实参:要求实参的顺序和形参的顺序相同。比如:
def describe_pet(animal_type,pet_name):
print("I have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet("hamster","harry")
#调用函数多次
describe_pet("dog","tony")
#关键字实参:是传递给函数的名称-值对。无需考虑函数调用中的实参顺序,还清楚的指出了函数调用中各个值的用途。比如:
def describe_pet(animal_type,pet_name):
print("I have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet(pet_name="lucy",animal_type="cat")
#默认值:可以给每个形参指定默认值。在调用函数中给形参提供了实参时,python将使用指定的实参值;否则,将使用形参的默认值。因此,给形参指定默认值后,可在函数
#调用中省略相应的实参。注意:使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的形参,能够让python更好的解读位置参数。比如:
def describe_pet(pet_name,animal_type="dog"):
print("I have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet("xiha")
describe_pet(pet_name="wangcai")
describe_pet("hurry","hamster")
describe_pet(pet_name="lucy",animal_type="cat")
describe_pet(animal_type="panda",pet_name="panpan")
#返回值:函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。在函数中,使用return语句将值返回到调用函数的代码行。比如:
"""函数get_formatted_name()的定义通过形参接受名和姓"""
def get_formatted_name(first_name, last_name):
"""将姓和名合二为一存储在变量full_name中"""
full_name = first_name+" "+last_name
"""将full_name的值转换为首字母大写的格式,将结果返回到函数调用行"""
return full_name.title()
"""调用返回值的函数,将返回值存储在变量musician中"""
musician = get_formatted_name("Jimi", "Hendrix")
"""输出变量musician"""
print(musician)
#让实参变成可选的。比如:
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)
#返回字典,比如:
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=27)
print(musician)
#函数结合while循环,比如:
def get_formatted_name(first_name, last_name):
full_name = first_name+" "+last_name
return full_name.title()
while True:
print("Please tell me your name(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
musician = get_formatted_name(f_name,l_name)
print("Hello "+musician+" !")
#传递列表,比如;
def greet_user(names):
for name in names:
print(name)
user_names=["rose",'jack','tony']
greet_user(user_names)
#在函数中修改列表,比如:
def print_models(unprinted_designs,completed_models):
"""
模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移动到列表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("The following models have been printed:")
for completed_model in completed_models:
print(completed_model)
"""
robot pendant:机器人吊坠;
dodecahedron:十二面体
"""
unprinted_designs = ["iphone case", "robot pendant", "dodecahedron"]
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
#传递任意数量的实参,比如:
def make_pizza(*toppings):
"""形参名*toppings中的星号让python创建一个名为toppings的空元组,并将所有值都封装到这个元组中"""
print("Making a pizza with the following toppings:")
for topping in toppings:
print(topping)
make_pizza("pepperoni")
make_pizza("mushrooms", "green peppers", "extra cheese")
#结合使用位置实参和任意数量实参,比如:
#注意:如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。
def make_pizza(size ,*toppings):
print("Make a "+str(size)+"-inch pizza with the following toppings:")
for top in toppings:
print(top)
make_pizza(16, "pepperoni")
make_pizza(12, "mushrooms", "green peppers", "extra cheese")
#使用任意数量的关键字实参,比如:
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)
#将函数存储在模块中:使用import语句允许在当前运行的程序文件中使用模块中的代码。比如:
"""在pizza.py所在的目录中创建一个名为make_pizzas.py的文件,写入以下代码:"""
def make_pizza(size,*toppings):
print("Make a "+str(size)+"-inch pizza with the following toppings:")
for top in toppings:
print(top)
"""导入刚创建的模块pizza,调用make_pizza两次"""
import pizza
pizza.make_pizza(16, "pepperoni")
pizza.make_pizza(12, "mushrooms", "green peppers", "extra cheese")
"""
原理:python读取这个文件时,代码行import pizza让python打开文件pizza.py,并将其中的所有函数都复制到这个程序中。
调用方法:模块名.函数名()
"""
#如果模块中有多个函数,可以导入特定的函数,导入方法如下:
"""
from 模快名 import 函数名
from pizza import make_pizza,make_pizza1,make_pizza2
"""
#使用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")