《python crash course》笔记(5)

函数

1. 定义函数

  1.1 简单打印函数

def greet_user(): # 定义函数名称,注意加冒号
    print("Hello") # 缩进内容添加函数内容
   
greet_user('jesse') #调用函数

  1.2 向函数传递参数

def greet_user(username): # username为形参(parameters)
    """Display a simple greeting.""" 
    print("Hello, " + username.title() + "!")
    
greet_user('jesse') # 'jesse'为实参(arguments)

2. 传递实参

  2.1 位置实参

    即调用函数时实参的顺序基于定义函数时形参的顺序

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') 
# 'hamster'和'harry'分别对应形参animal_type和pet_name,不能弄反,这就是位置实参

  2.2 关键字实参

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(animal_type='hamster', pet_name='harry') 
describe_pet(pet_name='harry',animal_type='hamster')
# 即调用时指定形参名,这时候无所谓顺序,上面两行的调用方法都正确,注意关键字中等号两边不要有空格!!

  2.3 默认值

# 在定义函数时给形参赋值,即默认值,指定默认值的等号两边不要有空格!!
def describe_pet(animal_type, pet_name='Jerry'): 
   """显示宠物的信息""" 
   print("
I have a " + animal_type + ".") 
   print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet(animal_type='hamster') # 调用时如果没有给pet_name指定值,那么它会默认为'Jerry'
describe_pet('hamster') # 位置实参调用,等效于上一行

  2.4 让实参变为可选的

def build_person(first_name, last_name, age=''): # age默认为空
    """Return a dictionary of information about a person."""
    person = {'first': first_name, 'last': last_name}
    if age:       # 使用if语句让age变为可选
        person['age'] = age
    return person

musician = build_person('jimi', 'hendrix') #若未指定age的值,则将不会打印出age相关的值
print(musician)
musician = build_person('jimi', 'hendrix',27) # 若指定age的值,则输出的字典包含age的值
musician = build_person('jimi', 'hendrix',age=27) # 等效于上一行
print(musician)

3. 返回值

  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 build_person(first_name, last_name):
    """Return a dictionary of information about a person."""
    person = {'first': first_name, 'last': last_name}
    return person
    
musician = build_person('jimi', 'hendrix')
print(musician)

    增加一个可选形参age如下

def build_person(first_name, last_name, age=''):
    """Return a dictionary of information about a person."""
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person

musician = build_person('jimi', 'hendrix', age=27)
print(musician)

  3.3 结合使用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:")  
    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("
Hello, " + formatted_name + "!") 

4. 传递列表

  4.1 简单传递列表

def greet_users(names):
    """向列表中的每位用户都发出简单的问候"""  
    for name in names:
        msg = "Hello, " + name.title() + "!"  
        print(msg) 

usernames = ['hannah', 'ty', 'margot'] 
greet_users(usernames)

  4.2 在函数中修改列表

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)
    return completed_models
def show_completed_models(completed_models):
    print("
The 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)

  4.3 避免修改列表

     接4.2,上述代码调用print_models()函数时会同时改变或者说清空原来的unprinted_designs列表,为了避免这一修改,可以         采取以下方式调用

print_models(unprinted_designs[:],completed_models) # 加上[:]创建列表的副本

    创建副本虽然可以避免修改原来的列表,但会消耗时间和内存,除非有充分理由,否则不需要创建副本

5. 传递任意数量的实参

def make_pizza(*toppings):
    """打印顾客点的所有配料"""    
    print(toppings)
    
make_pizza('pepperoni') 
make_pizza('mushrooms', 'green peppers', 'extra cheese')

    在形参toppings前面加上*号让python创建一个名为toppings的空元组,从而达到传递任意数量实参的效果

  5.1 结合使用位置实参和任意数量形参

def make_pizza(size, *toppings):
    """Summarize the pizza we are about to make."""
    print("
Making 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')

  5.2 结合使用关键字和任意数量实参

def build_profile(first, last, **user_info):
    """Build a dictionary containing everything we know about a user."""
    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)

6. 将函数存储到模块中

   模块即扩展名为.py的文件,文件中包含定义的各种函数,相当于封装库了,优点当然是将重点放在程序的高层逻辑上,让主       程序容易理解

  6.1 导入整个模块

     现在举例说明,现在当前目录(至于在不同目录下导入模块的方法,见下创建pizza.py,里面定义一个make_pizza函数,如下

    pizza.py

def make_pizza(size, *toppings):
    """Summarize the pizza we are about to make."""
    print("
Making a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

   然后在当前目录下新建make_pizza.py,并在里面导入pizza.py整个模块

   make_pizza.py

import pizza # 导入"pizza.py"模块

pizza.make_pizza(16, 'pepperoni') # 调用函数方式为"模块名+.+函数名"
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

  6.2 导入特定的函数

# 导入单个特定函数格式如下
# from module_name import function_name 

# 导入多个特定函数时用逗号隔开
#from module_name import function_0, function_1, function_2

# 下面以"make_pizza.py"举例

from pizza import make_pizza 
make_pizza(16, 'pepperoni') # 导入特定函数之后就无需使用句点"."
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

  6.3 使用as给函数指定别名

    make_pizza.py

from pizza import make_pizza as mp  # 指定函数别名为mp

mp(16, 'pepperoni') 
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

  6.4 使用as给模块指定别名

    make_pizza.py

import pizza as p # 给pizza模块指定别名p,注意只在当前文件有效,不会改变pizza.py的文件名

p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

  6.5 导入模块的所有函数

    make_pizza.py

from pizza import *  # 用星号表示导入所有函数

make_pizza(16, 'pepperoni') 
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

   然而这种方式并不推荐,因为在大型项目中很可能出现函数同名从而相互覆盖继而造成混乱的情况,所以这种情况还是用导入     整个模块的方法较为合适

原文地址:https://www.cnblogs.com/hzcya1995/p/13281759.html