Python编程从入门到实践(第八章函数)学习总结:

第八章函数
1、定义函数并传递参数
2、传递位置实参
3、传递关键字实参(名称:值 对)
4、默认值
5、函数return语句将值返回到调用函数的代码行
6、让实参变成可选的
7、返回字典(函数可返回任何类型的值,列表,字典等)
8、结合使用函数和while循环
9、将函数传递给列表
10、禁止函数修改列表,向函数传递列表的副本而不是原件
11、传递任意数量的实参
12、结合使用位置实参和任意数量实参
13、使用任意数量的关键字实参
14、函数存储在模块中,然后导入整个模块
15、导入模块中特定的函数语法
16、使用as给函数指定别名
17、导入模块中的所有函数
18、函数编写指南

1、定义函数并传递参数

def greet_user(username): #定义函数和一个形参
    print("Hello, "+ username.title() + "!")  #函数体的功能
greet_user('alice')   #调用函数时,传递一个实参

#输出结果:

Hello, Alice!

################
2、传递位置实参
#Python将函数调用中的每个实参都关联到函数定义中的一个形参

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')
describe_pet('dog','wangcai')

#输出结果:

I have a hamster!
My hamster's name is Harry.

I have a dog!
My dog's name is Willie.

I have a dog!
My dog's name is Wangcai

################
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='wangcai',animal_type='dog')    #即使顺序反了,明确的值是对的

#输出结果:

I have a hamster!
My hamster's name is Harry.

I have a dog!
My dog's name is Wangcai.

################
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('harry')  #位置实参,所以函数定义的时候对应的形参放前面了

#输出结果:

I have a dog!
My dog's name is Harry.

#使用默认值时,在形参列表中必须先列没有默认值的形参,再列出有默认值的形参,这样Python能够正确解读位置实参

################
5、函数return语句将值返回到调用函数的代码行

def get_formatted_name(first_name,last_name):
    full_name = first_name + " " + last_name
    return  full_name.title()  #return语句
musician = get_formatted_name('jimi','hendrix')
print(musician)

#输出结果:

Jimi Hendrix

################
6、让实参变成可选的

def get_formatted_name(first_name,last_name,middle_name=''):  #中间名可选,最后列出该形参,默认值设置为空
    if middle_name:  #middle_name 为非空时,表达式为True
        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')  #中间名放最后,Python才能将位置实参关联到形参
print(musician)

#输出结果:

Jimi Hendrix
John Lee Hooker

################
7、返回字典(函数可返回任何类型的值,列表,字典等)

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','hendirx',age = 27)
print(musician)

#输出结果:

{'first': 'jimi', 'last': 'hendirx', 'age': 27}

################
8、结合使用函数和while循环

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: john
Last_name: wang

Hello, John Wang!

Please tell me your name: 
(enter 'q' at any time to quit)
First_name: q

Process finished with exit code 0

################
9、将函数传递给列表

def greet_users(names):
    for name in names:
        msg = "Hello," + name.title()
        print(msg)
usernames = ['hannah','john','tom']
greet_users(usernames)  #将一个列表传给names形参

#输出结果:

Hello,Hannah
Hello,John
Hello,Tom

#在函数中修改列表

def print_models(unprint_designs,complete_models):
    while unprint_designs:   #只要传入的打印列表不为空,该表达式为True
        current_design = unprint_designs.pop()   #取出未打印的值
        print("Printing model: " + current_design)
        complete_models.append(current_design)   #将未打印的值添加到已完成打印的变量

def show_completed_models(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)  #调用print_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

################
10、禁止函数修改列表,向函数传递列表的副本而不是原件
function_name(list_name[:])
切片表示法[:]创建列表的副本

################
11、传递任意数量的实参

def make_pizza(*toppings): #形参名中的*号让Python创建一个空元组,将收到的所有值都封装到这个元组中
    print(toppings)
make_pizza("pepperoni")
make_pizza("mushrooms","green peppers",'cheese')

#输出结果:

('pepperoni',)
('mushrooms', 'green peppers', 'cheese')

################
12、结合使用位置实参和任意数量实参

def make_pizza(size,*toppings): #接收任意数量实参的形参放在最后,Python先匹配位置实参和关键字实参
    print("\nMaking a " + str(size) + " inch pizza with the following toppings: ")
    for topping in toppings:
        print(topping)
make_pizza(16,"pepperoni")  #将第一个值存储在形参size中,其他的存储在元组toppings中
make_pizza(14,"mushrooms","green peppers",'cheese')

#输出结果:

Making a 16 inch pizza with the following toppings: 
pepperoni

Making a 14 inch pizza with the following toppings: 
mushrooms
green peppers
cheese

################
13、使用任意数量的关键字实参

def build_profile(first,last,**user_info):  #定义要求提供姓和名,根据需要提供任意数量的键值对,**时让Python创建一个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', 'key': 'physics'}

################
14、函数存储在模块中,然后导入整个模块

def make_pizza(size,*toppings):   #创建一个扩展名为pizza.py的模块文件
    print("Making a " + str(size) + "-inch pizza with the following toppings: ")
    for topping in toppings:
        print("- " + topping)

import pizza   #通过import pizza导入之前的模块文件pizza.py;通过模块名.函数名()来使用函数
pizza.make_pizza(16,'peoperoni')
pizza.make_pizza(12,'mushrooms','greenpeppers')

#输出结果

Making a 16-inch pizza with the following toppings: 
- peoperoni
Making a 12-inch pizza with the following toppings: 
- mushrooms
- greenpeppers

################
15、导入模块中特定的函数语法
from module_name import function_name,function_name2 #通过用逗号分隔函数名,从而导入多个函数

def make_pizza(size,*toppings):   #创建一个扩展名为pizza.py的模块文件
    print("Making a " + str(size) + "-inch pizza with the following toppings: ")
    for topping in toppings:
        print("- " + topping)

from pizza import make_pizza
make_pizza(16,'peoperoni')   #因为import显式的导入了函数make_pizza,因此调用时无需使用pizza.make_pizza格式
make_pizza(12,'mushrooms','greenpeppers')

#输出结果

Making a 16-inch pizza with the following toppings: 
- peoperoni
Making a 12-inch pizza with the following toppings: 
- mushrooms
- greenpeppers

################
16、使用as给函数指定别名

def make_pizza(size,*toppings):   #创建一个扩展名为pizza.py的模块文件
    print("Making a " + str(size) + "-inch pizza with the following toppings: ")
    for topping in toppings:
        print("- " + topping)

import pizza as p #导入某个模块时,给某个模块指定别名(与下一行二选一)
from pizza import make_pizza as mp #给模块中的某个函数指定别名
mp(16,'peoperoni')
mp(12,'mushrooms','greenpeppers')

#输出结果

Making a 16-inch pizza with the following toppings: 
- peoperoni
Making a 12-inch pizza with the following toppings: 
- mushrooms
- greenpeppers

################
17、导入模块中的所有函数

def make_pizza(size,*toppings):   #创建一个扩展名为pizza.py的模块文件
    print("Making a " + str(size) + "-inch pizza with the following toppings: ")
    for topping in toppings:
        print("- " + topping)

from pizza import * #使用星号(*)导入模块中的所有函数
make_pizza(16,'peoperoni')    ##不建议使用,如果与现有项目重名,会覆盖函数,最好是 模块.方函数名 调用
make_pizza(12,'mushrooms','greenpeppers')

#输出结果

Making a 16-inch pizza with the following toppings: 
- peoperoni
Making a 12-inch pizza with the following toppings: 
- mushrooms
- greenpeppers

################
18、函数编写指南
18.1 给函数指定描述性名称,且只在其中使用小写字母和下划线
18.2 每个函数都应包含简要的阐述其功能的注释,注释后应紧跟在函数定义后面,并采用文档字符串格式
18.3 给形参指定默认值时,等号两边不要有空格
18.4 对于函数调用中的关键字实参,应遵循function_name(value_0,parameter_1=‘value’)

Python编程从入门到实践基础知识:https://blog.csdn.net/louzhu_lz/article/details/90721685
Python编程从入门到实践(第三、四章的列表和元祖):https://blog.csdn.net/louzhu_lz/article/details/91354506
Python编程从入门到实践(第五章if语句学习总结):https://blog.csdn.net/louzhu_lz/article/details/91409903
Python编程从入门到实践(第六章字典学习总结):https://blog.csdn.net/louzhu_lz/article/details/91910554
Python编程从入门到实践(第七章用户输入和while循环学习总结):https://blog.csdn.net/louzhu_lz/article/details/92384649

你可能感兴趣的:(Python入门)