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.