《Python编程:从入门到实践》知识点 第8章 函数

《Python编程:从入门到实践》知识点 第2-4章

《Python编程:从入门到实践》知识点 第5-7章

第8章 函数

定义函数 传递实参

在这里插入图片描述

def pet(name, aniaml_type = 'dog'):
    """宠物的信息"""
    print("\nMy " + aniaml_type + "'s name is " + name + ".")

pet('jack')
pet(name='jack')

pet('harry', 'hamster')
pet(aniaml_type='hamster', name='harry')
pet(name='harry', aniaml_type='hamster')
#运行结果
My dog's name is jack.

My dog's name is jack.

My hamster's name is harry.

My hamster's name is harry.

My hamster's name is harry.

返回值

def person(name, age = ''):
    """人的信息,返回一个字典"""
    person = {'name': name}
    if age:
        person['age']= age
    return person

musician = person('jimi')
player = person('lucy', age=21)
print(musician)
print(player)
#运行结果
{'name': 'jimi'}
{'name': 'lucy', 'age': 21}

传递任意数量的实参

#形参名*toppings创建一个空元组,将所有值都装到这个元组里
def make_pizza(size, *toppings):
    """概述要制作的披萨"""
    print("\n Making a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza(12,'mushrooms', 'green peppers', 'extra cheese')
#运行结果
 Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
#形参名*toppings创建一个空元组,将所有值都装到这个元组里
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'}

将函数存在模块中

#导入模块
import pizza
pizza.make_pizza(16,'mushrooms')

#导入模块的特定函数
from pizza import make_pizza
make_pizza(16,'mushrooms')

在这里插入图片描述

#导入模块
import pizza as p
p.make_pizza(16,'mushrooms')

#导入模块的特定函数
from pizza import make_pizza as mp
mp(16,'mushrooms')

在这里插入图片描述

from pizza import *
pizza.make_pizza(16,'mushrooms')

函数编写指南

在这里插入图片描述

def function_name(
        para0,para1,para2,
        para3,para4,para5):
    function body...

《Python编程:从入门到实践》知识点 第9章 类

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值