一 函数是什么?
函数一词来源于数学,但编程中的「函数」概念,与数学中的函数是有很大不同的,具体区别,我们后面会讲,编程中的函数在英文中也有很多不同的叫法。在BASIC中叫做subroutine(子过程或子程序),在Pascal中叫做procedure(过程)和function,在C中只有function,在Java里面叫做method。
函数能提高应用的模块性,和代码的重复利用率。你已经知道Python提供了许多内建函数,比如print()。但你也可以自己创建函数,这被叫做用户自定义函数。
定义: 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可
特性:
1.代码重用
2.保持一致性
3.可扩展性
二 函数的创建
2.1 格式:
Python 定义函数使用 def 关键字,一般格式如下:
def 函数名(参数列表):
函数体
def hello():
print('hello')
hello()#调用
2.2 函数名的命名规则:
- 函数名必须以下划线或字母开头,可以包含任意字母、数字或下划线的组合。不能使用任何的标点符号;
- 函数名是区分大小写的。
- 函数名不能是保留字。
2.3 形参和实参
形参:形式参数,不是实际存在,是虚拟变量。在定义函数和函数体的时候使用形参,目的是在函数调用时接收实参(实参个数,类型应与实参一一对应)
实参:实际参数,调用函数时传给函数的参数,可以是常量,变量,表达式,函数,传给形参
区别:形参是虚拟的,不占用内存空间,.形参变量只有在被调用时才分配内存单元,实参是一个变量,占用内存空间,数据传送单向,实参传给形参,不能形参传给实参
import time
times=time.strftime('%Y--%m--%d')
def f(time):
print('Now time is : %s'%times)
f(times)
2.4 实例
实例1:
def show_shopping_car():
saving=1000000
shopping_car=[
('Mac',9000),
('kindle',800),
('tesla',100000),
('Python book',105),
]
print('您已经购买的商品如下'.center(50,'*'))
for i ,v in enumerate(shopping_car,1):
print('\033[35;1m %s: %s \033[0m'%(i,v))
expense=0
for i in shopping_car:
expense+=i[1]
print('\n\033[32;1m您的余额为 %s \033[0m'%(saving-expense))
show_shopping_car()
实例2:
现在我们就用一个例子来说明函数的三个特性:
def action1(n): print ('starting action1...') with open('日志记录','a') as f: f.write('end action%s\n'%n) def action2(n): print ('starting action2...') with open('日志记录','a') as f: f.write('end action%s\n'%n) def action3(n): print ('starting action3...') with open('日志记录','a') as f: f.write('end action%s\n'%n) action1(1) action2(2) action3(3) ##***************代码重用 def logger(n): with open('日志记录','a') as f: f.write('end action%s\n'%n) def action1(): print ('starting action1...') logger(1) def action2(): print ('starting action2...') logger(2) def action3(): print ('starting action3...') logger(3) action1() action2() action3() ##***************可扩展和保持一致 ##为日志加上时间 import time def logger(n): time_format='%Y-%m-%d %X' time_current=time.strftime(time_format) with open('日志记录','a') as f: f.write('%s end action%s\n'%(time_current,n)) def action1(): print ('starting action1...') logger(1) def action2(): print ('starting action2...') logger(2) def action3(): print ('starting action3...') logger(3) action1() action2() action3()