python学习笔记:第八章 函数(一)

󰃭 2017-04-20

python学习笔记:第八章 函数(一)


定义和传递,实参和形参


def greet_user(username):    #username 是形参
    """显示简单的问候语"""
    print("Hello," + username.title() + "!")

greet_user('jesse')     #'jesse'是实参   实参被存储在形参username中

传递实参

位置实参

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(animal_type='hamster', pet_name='harry')

默认值

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

返回值

def get_formatted_name(first_name, last_name):
    full_name = first_name + ' ' + last_name
    return full_name.title()
#调用返回值时,需要提供一个变量,如musician
musician = get_formatted_name('jimi', 'hendrix')
print(musician)

#让实参变成可选的 定义时让可选参数为空。

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)

返回字典及扩展

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

函数和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 + "!")

传递列表

def greet_users(names):
    for name in names:
        msg = "Hello," + name.title() + "!"
        print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

在函数中修改列表

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

传递副本

print_models(unprinted_designs[:], completed_models)