Python-Functions

12 minute read

要执行函数定义的特定任务, 可调用 函数

8.1 定义函数

E.g: greeter.py

def greet_user():                           # Line 1
    """Show simple greetings"""             # Line 2
    print("Hello!")                         # Line 3
    
greet_user()                                # Line 4
Output:
Hello!

解释:

Line 1: def 表明你要定义一个函数, 后面缩进构成函数体 Line 2: 文档字符串, 由三个引号引起 Line 3: 函数代码 Line 4: 函数调用

8.1.1 向函数传递信息

E.g: improved_greeter.py

def greet_user(username):                           # A - 1
    """Show simple greeting message"""
    print("Hello, " + username.title() + "!")
    
greet_user('jesse')                                 # A - 2
Output:
Hello, Jesse!

8.1.2 实参和形参

A - 1 中, username 是一个形参 在 A - 2 中, 'jesse' 是一个实参

8.2 传递实参

8.2.1 位置实参

你调用函数时, Python 必须根据调用中的每个实参都关联到函数定义中的一个形参, 为此, 最简单的关联方式是基于实参的顺序 这种调用方式被称为 位置实参

E.g: pets.py

def describe_pet(animal_type, pet_name):
    """Show pets' information"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')
Output

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

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

8.2.2 关键字实参

E.g: new_pets.py

def describe_pet(animal_type, pet_name):
    """Show pets' information"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    
describe_pet(pet_name = 'harry', animal_type = 'hamster')
describe_pet('dog', 'willie')
Output is the same as above

8.2.3 默认值

E.g: new2_pets.py

def describe_pet(animal_type = 'dog', pet_name):
    """Show pets' information"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    
describe_pet(pet_name = 'harry', animal_type = 'hamster')
describe_pet(pet_name = 'willie')

Output

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

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

注: 使用默认值时, 在形参列表中必须先列出没有默认值的形参

8.2.4 等效的函数调用

注意到在之前的函数定义: def describe_pet(pet_name, animal_type = 'dog') 在任何情况下都必须给 pet_name 提供实参

略 23333

8.2.5 避免实参错误

8.3 返回值

8.3.1 简单返回值

E.g: formatted_name.py

def get_formatted_name(first_name, last_name):
    """Return Formatted Names"""
    full_name = first_name + ' ' + last_name
    
    return full_name.title()
    
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
Output
Jimi Hendrix

8.3.2 使实参可选

E.g:

def get_formatted_name(first_name, last_name, middle_name = '')

8.3.3 返回字典

E.g: person.py

def build_person(first_name, last_name, age = ''):
    """return a Dictionary"""
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person
    
musician = build_person('jimi', 'henrix', age = 27)
print(musician)
Output:
{'first': 'jimi', 'last': 'henrix', 'age': 27}

8.3.4 结合使用函数和 while 循环

E.g:

def get_formatted_name(first_name, last_name):
    """Return Formatted Names"""
    full_name = first_name + ' ' + last_name
    
    return full_name.title()

# Infinite Loop!
while True:
    print("\nPlease tell me your name: ")
    f_name = input("First name: ")
    l_name = input("Last name: ")
    
    formatted_name = get_formatted_name(f_name, l_name)
    print("\nHello, " + formatted_name.title())

8.4 传递列表

E.g: greet_users.py

def greet_users(names):
    """Send greetings to everyone in the list"""
    for name in names:
        print("Hello, " + name.title() + "!")
        
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
Output:
Hello, Hannah!
Hello, Ty!
Hello, Margot!

8.4.1 在函数中修改列表

E.g: printing_models.py

def print_models(unprinted_designs, completed_models):
	""" ... """
	while unprinted_designs:
		current_design = unprinted_designs.pop()
		
		print("Print 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', 'rebot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
Output:
Print model: dodecahedron
Print model: rebot pendant
Print model: iphone case

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

8.4.2 禁止函数修改列表

Use function[:] to pass a copy of the list to a sunction 切片法表示创建列表副本

8.5 传递任意数量的实参

E.g: pizza.py

def make_pizza(*toppings):
    print(toppings)
    
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
Output:
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')

Explanation:

*toppings 创建了一个名为 toppings 的空元组, 并把所有值封装到元组中

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

E.g: new_pizza.py

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')
Output
Making a 16-inch pizza with the following toppings:
- pepperoni

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

Leave a comment