玩命加载中 . . .

python-函数


​ 8.1 定义函数

In [1]:

def greet_user():

    """显示简单的问候语"""

    print("Hello!")

greet_user()
Hello!

8.1.1 向函数传递信息

In [2]:

def greet_user(username):

    """显示简单的问候语"""

    print("Hello, " + username.title() + "!")

greet_user('jesse')
Hello, Jesse!

8.2.1 位置实参

In [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('hamster', 'harry')
I have a hamster.
My hamster's name is Harry.

1.调用函数多次

In [4]:

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')
I have a hamster.
My hamster's name is Harry.

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

2.位置实参的顺序很重要

In [5]:

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('harry', 'hamster')
I have a harry.
My harry's name is Hamster.

8.2.2 关键字实参

In [6]:

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')
I have a hamster.
My hamster's name is Harry.

8.2.3 默认值

In [7]:

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.

8.2.4 等效的函数调用

In [8]:

# 一条名为Willie的小狗

describe_pet('willie')

describe_pet(pet_name='willie')

#一只名为harry的仓鼠

describe_pet('harry', 'hamster')

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

describe_pet(animal_type='hamster',pet_name='harry')
I have a dog.
My dog's name is Willie.

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

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

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

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

8.2.5 避免实参错误

In [9]:

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()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-e79742ba0234> in <module>
      3     print("\nI have a " + animal_type + ".")
      4     print("My " + animal_type + "'s name is " + pet_name.title() + ".")
----> 5 describe_pet()

TypeError: describe_pet() missing 2 required positional arguments: 'animal_type' and 'pet_name'

8.3 返回值-return语句

In [10]:

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

In [11]:

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)
Jimi Hendrix
John Lee Hooker

8.3.2 让实参变成可选的

In [12]:

def get_formatted_name(first_name, middle_name, last_name):

    """返回整洁的姓名"""

    full_name = first_name + ' ' + middle_name + ' ' + last_name

    return full_name.title()

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

print(musician)
John Lee Hooker

8.3.3 返回字典

In [13]:

def build_person(first_name,last_name):

    """返回一个字典,其中包含有一个人的信息"""

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

    return person

musician = build_person('jimi', 'hendrix')

print(musician)
{'first': 'jimi', 'last': 'hendrix'}

8.3.4 结合使用函数和while循环

In [14]:

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: Edgar
Last name: ARI

Hello, Edgar Ari!

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

8.4 传递列表

In [15]:

def greet_users(names):

    """向列表中的每位用户都发出简单的问候"""

    for name in names:

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

        print(msg)

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

greet_users(usernames)
Hello, Hannsh!
Hello, Ty!
Hello, Margot!

8.4.1 在函数中修改列表

In [16]:

#为用户提交的设计制作3D打印模型的公司,需要打印的设计存储在一个列表中,打印后移到另一个列表中

#不使用函数

#先创建一个列表,其中包含一些要打印的设计

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']

completed_models = []

#模拟打印每个设计,直到没有未打印的设计为止

#打印每个设计 后,都将其移到列表completed_models中

while unprinted_designs:

    current_design = unprinted_designs.pop()

    #模拟根据设计制作3D打印模型的过程

    print("Printing model: " + current_design)

    completed_models.append(current_design)

#显示打印好的所有模型

print("\nThe following models have been printed:")

for completed_model in completed_models:

    print(completed_model)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case

The following models have been printed:
dodecahedron
robot pendant
iphone case

In [17]:

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)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case

The following models have been printed: 
dodecahedron
robot pendant
iphone case

8.5 传递任意数量的实参

In [18]:

def make_pizza(*toppings):

    """打印顾客点的所有配料"""

    print(toppings)

make_pizza('pepperoni')

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

In [19]:

def make_pizza(*toppings):

    """打印顾客点的所有配料"""

    print("\nMaking a pizza with the following toppings:")

    for topping in toppings:

        print("- " + topping)

make_pizza('pepperoni')

make_pizza('mushrooms', 'green peppers', 'extra cheese')
Making a pizza with the following toppings:
- pepperoni

Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

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

In [20]:

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

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

In [21]:

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)
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

8.6 将函数存储在模块中

可将python文件导入另一个python程序,同时,也可以通过as方法,给以导入的函数与模块别名,防止程序运行过程中发生的错误冲突


文章作者: Edgar
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Edgar !
评论
  目录