python基础(五)

1、传递实参

1.1 位置实参

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')

-->I have ahamster.

    My hamster's name is Harry.

注意:函数调用中实参的顺序与函数定义中形参的顺序一致

1.2 关键字实参

describe_pet(animal_type='hamster',pet_name='harry')

describe_pet(pet_name='harry',animal_type='hamster')

-->I have ahamster.

    My hamster's name is Harry.

    I have ahamster.

    My hamster's name is Harry.

注意:使用关键字实参时,务必准确地指定函数定义中的形参名

1.3 默认值

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.

注意:在调用函数中给形参提供了实参时,Python将使用指定的实参值;否则,将使用形参的默认值。在使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参,这让python能正确解读位置实参。

2、返回值

2.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)

-->Jimi Hendrix

2.2 让实参变得可选

def get_formatted_name(first_name,last_name,middle_name=''):    //先让中间名字形参默认为空

if middle_name:    //用if语句判断

    full_name=first_name+" "+middle_name+" "+last_name    //有中间名字时加上实参

else:

    full_name=first_name+" "+last_name

return full_name.title()

musician=get_formatted_name('jimi','hendrix2')

print(musician)

musician=get_formatted_name('john','hooker','lee')

print(musician)

-->Jimi Hendrix2

    John Lee Hooker

2.3 返回字典

def build_person(first_name,last_name):

    person={'first':first_name,'last':last_name}

    return person

musician=build_person('tom','smith')

print(musician)

-->{'first': 'tom', 'last': 'smith'}

3、传递列表

def greet_users(names):    //形参是一个列表

    for name in names:

        msg="Hello, "+name.title()+"!"

        print(msg)

usernames=['hahana','ty','margot']

greet_users(usernames)

-->Hello, Hahana!

    Hello, Ty!

    Hello, Margot!

3.1 在函数中修改列表

def print_models(unprinted_designs,completed_models):

    while unprinted_designs:

        current_design=unprinted_designs.pop()

        print("Printiing 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)

-->Printiing model: dodecahedron    //每个函数只负责一项具体的工作

    Printiing model: robot pendant

    Printiing model: iphone case

    The following models have been printed:

    dodecahedron

    robot pendant

    iphone case

4、传递任意数量的实参

def make_pizza(*toppings):    //形参*toppings中的星号让Python创建一个名为toppings的空元组

    print(toppings)    

make_pizza('pepperoni')

make_pizza('mushrooms','green peppers','extra cheese')

-->('pepperoni',)

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

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

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')

-->Making a 16-inch pizza with the following toppings:

    -pepperoni

    Making a 12-inch pizza with the following toppings:

    -mushrooms

    -green peppers

    -extra cheese

4.2 使用任意数量的关键字实参

def build_profile(first,last,**user_info):    #形参**user_info中的两个星号让Python创建一个空字典,须放于形参最后位置

    profile={}

    profile['first-name']=first

    profile['last-name']=last

    for k,v in user_info.items():

        profile[k]=v

    return profile

a=build_profile('albert','einstein',location='princeton',field='physics')

print(a)

-->{'first-name': 'albert', 'last-name': 'einstein', 'location': 'princeton', 'field': 'physics'}

5、将函数存储在模块中

5.1 导入整个模块

pizza.py

def make_pizza(size,*toppings):

    print("\nMaking a "+str(size)+"-inch pizza with the following toppings:")

    for topping in toppings:

        print("-"+topping)

同目录下making_pizza.py

import pizza     //引用pizza则pizza.py中所有函数都能用

pizza.make_pizza(16,'pepperoni')

pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')

5.2 导入特定的函数

from module_name import function_name

通过用逗号分隔函数名,导入任意数量的函数

from module_name import function_0,function_1,function_2

5.3 使用as给函数指定别名

from module_name import function_name as fn

5.4 使用as给模块指定别名

import module_name as mn

5.5 导入模块中的所有函数

from module_name import *    #星号(*)运算符可导入模块中的所有函数

注意:所有的import语句都应放在文件开头,唯一例外的情形是,在文件开头使用了注释来描述整个程序

你可能感兴趣的:(python基础(五))