live long and prosper
自定义函数
def greet_user():
"""现实简单的问候语"""
print("hello!")
greet_user()
首先关键字def是告诉python我要自定义一个函数,也就是函数定义,代码中的greet_user()则是自定义的函数命,
注意函数名后面要加上冒号表示函Markdown Preview Enhanced数体开始。
函数调用的话则是如8行中,直接书写函数名称即可调用
向函数传递信息
在上面的例子中函数只可以输出hello,调用函数时,使之可以传递名字
def greet_user(user_name):
"""现实简单的问候语"""
print("hello!")
print(user_name)
greet_user('harry potter')
传递名字或者字符串的时候注意将字符串加上单引号
实参和形参
在上面的例子中,user_name是一个形参,而harry potter则是实参
传递实参
函数定义中一般会有多个形参,因此需要向函数传递多个实参,这里有位置实参,和关键字实参
位置实参
使用位置实参传递时必须注意参数的顺序,切记不能混乱
def pet(pet_type, pet_name):
"""传递宠物的种类和名字"""
print(f"I have a {pet_type}")
print(f"My {pet_type}'name is {pet_name}")
pet('dog', 'penny')
在这个例子中向函数传递了宠物的种类和名字,dog和penny
####多次调用函数时,只需要重复函数调用操作即可
def pet(pet_type, pet_name):
"""传递宠物的种类和名字"""
print(f"I have a {pet_type}")
print(f"My {pet_type}'name is {pet_name}")
pet('dog', 'penny')
pet('cat','burly')
关键字实参
关键字实参需要直接书写名字值对,即’‘pet_type=‘dog’, pet_name=‘harry’’,再次声明,使用关键字实参务必准确的指定函数定义的形参名
def pet(pet_type, pet_name):
"""传递宠物的种类和名字"""
print(f"I have a {pet_type}")
print(f"My {pet_type}'name is {pet_name}")
pet(pet_type='dog', pet_name='harry')
默认值
编写函数时,可以为形参指定默认值,这样当形参调用频繁并且调用值相同的时候,可以将调用之设定为默认值
def pet(pet_name, pet_type='dog'):
"""传递宠物的种类和名字"""
print(f"I have a {pet_type}")
print(f"My {pet_type}'name is {pet_name}")
pet(pet_name='harry')
在调用函数时,如果没有对有默认值的形参传递实参,则使用默认值
在使用默认值的函数调用中注意,因为python仍然将按照位置传递实参,所以在上面的例子中将pet_name放在pet_type的
前面,那么在函数调用传递实参时,就不会将’harry’传递给了pet_type,而pet_type则传递默认值
使用默认值时,在形参列表中先列出没有默认值的形参,在列出有默认值的形参
函数返回值
返回简单值
自定义函数,使之能够返回一个或一组值。函数返回的值称为返回值,在函数中,使用return将值返回到调用函数的代码行
def get_name(first_name, last_name):
"""返回完整的名字"""
full_name = f"{first_name} {last_name}"
return full_name.title()
print(get_name('harry', 'potter'))
当需要使用返回值时,可以直接调用函数
让实参变成可选值
如果需要使用get_name函数能够处理中间名,
def get_name(first_name, last_name, middle_name=''):
"""返回完整的名字"""
if middle_name:
full_name = f"{first_name} {middle_name} {last_name}"
else:
full_name = f"{first_name} {last_name}"
return full_name.title()
print(get_name('harry', 'potter', 'snap'))
print(get_name('harry', 'potter'))
注意要将有默认值的形参放在后面
返回字典
def build_person(first_name, last_name):
"""返回一部字典,其中包含一个人的信息"""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('harry', 'potter')
print(musician)
扩展上面的函数,时期能够接受可选值,例如年龄
def build_person(first_name, last_name,age=None):
"""返回一部字典,其中包含一个人的信息"""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
musician = build_person('harry', 'potter',age=18)
print(musician)
结合使用while循环与自定义函数
def get_name(first_name, last_name):
full_name = f"{first_name} {last_name}"
return full_name.title()
while True:
print("please input first name and last name.")
print("enter 'q' at any time to quit.")
first_name = input("the first name:")
if first_name == 'q':
break
last_name = input("the last name:")
if last_name == 'q':
break
full_name = get_name(first_name, last_name)
print(f"Hello {full_name}")
同时在该例中给予用户选择何时退出程序
传递列表
之前我们学习了向函数传递字符串等等,现在学习向函数传递列表
def greet_user(names):
for name in names:
print(f"Hello {name.title()}")
names = ['sdc', 'sc', 'regex']
print(greet_user(names))
以下是生成结果
Hello Sdc
Hello Sc
Hello Regex
None
禁止修改列表
为了数据安全,避免函数可能破坏原始数据(列表),需要禁止函数修改列表,可以向函数传递列表的副本,使用切片,如list_name[:]可以创建列表的副本
传递任意数量的实参
使用自定义函数时,可能不知道要向函数传递多少实参,python允许我们采取下列方式,从调用语句中收集任意数量的实参
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
形参中的*toppings中的星号让python创建了一个名为toppings的空元组,可以收到的所有值封装到元组中
如果需要打印元组,则将print语句替换为for循环语句即可
结合使用位置实参和任意数量实参
def make_pizza(size,*toppings):
print(f"make a {size} inch pizza with the following toppings:")
for topping in toppings:
print(f"-{topping}")
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
在该例中将位置实参与任意数量实参相结合,同时在以后的程序编写中经常会看到*args做为通用形参名,收集任意数量的位置实参
创建任意数量的关键字形参
def build_profile(first, last, **user_info):
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('harry', 'potter',
location='london',
field='magic'
)
print(user_profile)
在上面的例子中,形参**user_into让python创建一个空字典,并且将所有的名称值对都放在这个字典中,返回的字典中不仅有姓名,还有地址和专业。
**kwargs在python常常用于收集任意数量的关键字形参
将函数储存在模块中
将函数储存在成为模块中的独立文件中,可以将函数代码块与主函数分离,使整个项目更加具有条理,需要使用函数要将函数模块导入到主程序中。
###导入整个模块
注意,创建函数模块,需要在同一个文件路径下创建两个py文件,一个时主程序文件,一个是函数模块文件。
这里,我创建两个文件:主:main.py文件和函数模块:func.py文件。
main.py:
import func
func.func(12,'wedcv','dec','wevdw')
func.py:
def func(size,*toppings):
print(f"you want {size} of pizza with:")
for topping in toppings:
print(topping)
首先需要书写
import (函数模块文件名)
语句,以便导入函数模块。在主程序调用函数时,书写
函数模块文件名.自定义函数名(函数形参)
###导入特定的函数
从模块中导入特定函数,语法为:
from 模块名 import 函数名
使用逗号将函数名分割开可调用任意数量函数
from 模块名 import 函数1,函数2,函数3
如果导入了特定的函数,调用函数时无需书写函数模块文件名和句点直接书写
函数名.(函数形参)
###使用as为函数指定别名
from model_name import func_name as fn
###使用as为模块指定别名
import model_name as mn
###导入模块中的所有函数
使用*运算符可以导入模块中的所以函数
from model_name import *
欢迎斧正。