Python入门笔记:函数

def那行要跟:
"""something"""用三个引号引起,文档字符串的注释。

def great_user(username):
    """显示简单的问候语"""
    print('Hello, ' + username.title() + "!")

great_user('jesse')

这里写图片描述

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(pet_name = 'willie', animal_type = 'dog')  #关键字实参

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('haha')
describe_pet(pet_name='lala')
describe_pet('xixi','pig')
describe_pet(animal_type='cat',pet_name='dudu')

这里写图片描述

def build_person(first_name, last_name, age=''):  #age可选形参
    """返回一个字典,其中包含有关一个人的信息"""
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person

musician = build_person('jimi', 'hedrix', age=27)
print(musician)
someone = build_person('lala', 'xixi', 30)
anotherone = build_person('dudu' ,'haha')
print(someone)
print(anotherone)

这里写图片描述

将列表传递给函数之后,函数就可以对其进行修改。
用切片表示法[:]创建列表的副本,将列表的副本传递给函数,函数所做的修改就不会影响原来的列表。
除非有充分理由需要保留原始列表的内容,创建副本需要花费时间和内存,特别是大型列表

def build_profile(first, last, *topping, **user_info):
    """测试接受任意数量的参数"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    print(topping)
    for key,value in user_info.items():
        profile[key] = value
    return profile

print(build_profile('haha','lala','xixi','dudu','didi',location='cn',test='some'))

这里写图片描述
一个*的形参表示可以接受任意数量的参数,传递给参数时,任意数量的实参会转化为元组。
**的形参表示可以接受任意数量的键值对,传递给参数时,会转换成字典。

将函数存储在模块中,模块是扩展名为.py的文件。
import module
module.function()

from module import function1, function2, ...
function()

from module import function as alias
alias()

import module as alias
alias.function()

from module import *一般不使用
函数是覆盖的,同名函数后面出现会覆盖前面的。

如果觉得此文章有用,点击这里,万分感谢。
这里写图片描述

Reference

[美]Eric Matthes著,袁国忠译. Python编程从入门到实践[M]. 北京:人民邮电出版社. 2016.7.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值