08_python_函数


日期:2017-12-30 作者:秋的懵懂



# coding = utf-8

# ***********************************************************
# @file       python_08_function.py
# @brief      函数
# @author     魏文应
# @date       2017-12-27
# ***********************************************************



# ---------------------------------------------------------
# 定义函数
print('\n\n')
print('_______________________________________________')
print("定义函数:")

# 定义函数
def greet_user():
    """显示问候语"""
    print('hello!')
# 使用函数
greet_user()

print('_______________________________________________')
# ---------------------------------------------------------




# ---------------------------------------------------------
# 给函数传一个参数
print('\n\n')
print('_______________________________________________')
print("给函数传一个参数:")

# 定义函数,定义时称为形参
def greet_user(username):
    """显示问候语"""
    print('hello! ' + username.title() + '.')

# 使用函数,使用时称为实参
greet_user('魏文应')

print('_______________________________________________')
# ---------------------------------------------------------




# ---------------------------------------------------------
# 实参
print('\n\n')
print('_______________________________________________')
print("实参:")

def describe_pet(animal_type, pet_name):
    """显示动物信息"""
    print('My ' + animal_type + "'s name is " + pet_name + '.')

# 根据位置,把实参关联到形参上
describe_pet('hamster', 'harry')

# 关键字实参
describe_pet(animal_type='hamster', pet_name='harry')

# 指定默认值,如果前面参数没有默认值,
# 有默认值的参数需要放在后面
def describe_pet(pet_name, animal_type = 'dog'):
    """显示动物信息"""
    print('My ' + animal_type + "'s name is " + pet_name + '.')

describe_pet(pet_name='Willie')
describe_pet('Willie')

print('_______________________________________________')
# ---------------------------------------------------------



# ---------------------------------------------------------
# 函数返回值
print('\n\n')
print('_______________________________________________')
print("函数返回值:")

def get_formatted_name(fisrt_name, last_name):
    """返回完整的名字"""
    full_name = fisrt_name + ' ' + last_name
    
    return full_name.title()

musician = get_formatted_name('jimi', 'handrix')
print(musician)

# 让实参变成可选的
def get_formatted_name(fisrt_name, last_name, 
        middle_name = ''):
    """返回完整的名字"""
    if middle_name:
        full_name = fisrt_name + ' ' + middle_name + \
            ' ' + last_name
    else:
        full_name = fisrt_name + ' ' + last_name
        
    return full_name.title()
    
musician = get_formatted_name('jimi', 'handrix')
print(musician)

musician = get_formatted_name('jimi', 'handrix', 'lee')
print(musician)

print('_______________________________________________')
# ---------------------------------------------------------




# ---------------------------------------------------------
# 返回值为字典类型
print('\n\n')
print('_______________________________________________')
print("返回值为字典类型:")

def build_person(first_name, last_name, age=''):
    """返回一字典,包含人的信息"""
    person = {'first': first_name, 'last': last_name}
    
    # 可参数age
    if age:
        person['age'] = age
    
    return person
    
musician = build_person('jimi', 'handrix')
print(musician)

musician = build_person('jimi', 'handrix', 27)
print(musician)

print('_______________________________________________')
# ---------------------------------------------------------





# ---------------------------------------------------------
# 函数参数为列表
print('\n\n')
print('_______________________________________________')
print("函数参数为列表:")

def print_models(unprinted_designs, complete_models):
    """打印信息"""
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print('Printing model:' + current_design)
        complete_models.append(current_design)

def show_complete_models(complete_models):
    """打印信息"""
    print('\nThe following models have been printed:')
    for complete_model in complete_models:
        print(complete_model)


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

# 这里unprinted_designs传了列表副本,列表不会被修改
print_models(unprinted_designs[:], completed_models)
show_complete_models(completed_models)
show_complete_models(unprinted_designs)

# 直接传列表参数名,列表会被修改
print_models(unprinted_designs, completed_models)
show_complete_models(completed_models)
show_complete_models(unprinted_designs)

print('_______________________________________________')
# ---------------------------------------------------------




# ---------------------------------------------------------
# 传递任意数量参数
print('\n\n')
print('_______________________________________________')
print("传递任意数量参数:")

# *toppings是一个空元组
def make_pizza(*toppings):
    print(toppings)

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

print('_______________________________________________')
# ---------------------------------------------------------





# ---------------------------------------------------------
# 传递任意数量参数(字典)
print('\n\n')
print('_______________________________________________')
print("传递任意数量参数(字典):")

# **user_info 创建一个空字典
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)

print('_______________________________________________')
# ---------------------------------------------------------




# ---------------------------------------------------------
# 将函数存储在模块中
print('\n\n')
print('_______________________________________________')
print("将函数存储在模块中:")

# import导入的文件不能是以数字开头命名的
# 如果文件名过长,可用pizza 替代
# python_08_function_pizza,如下
# 指定别名
import python_08_function_pizza as pizza

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

# 只导入其中一个函数
# from module_name import function_0, function_1, function_2
# * 号可以导入所有函数
# from python_08_function_pizza import *
from python_08_function_pizza import make_pizza

make_pizza(13, 'pepperoni')

print('_______________________________________________')
# ---------------------------------------------------------



子模块:


# coding = utf-8

# ***********************************************************
# @file         python_08_function_pizza.py
# @brief        函数模块
# @author       魏文应
# @date         2017-12-28
# ***********************************************************



def make_pizza(size, *toppings):
    """概述要制作的蛋糕"""
    print('\nMake a ' + str(size) + 
          '-inch pizza with the following toppings:')
    for topping in toppings:
        print('-' + topping)




©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容