一、一些简单的基础概念
- 特征:可重复使用、有特定功能
- 调用方式:函数名(参数)
- 函数尽量都要有返回值
- 创建方式
#1.参数可有可无。
#2.python中通常使用_funcName_的形式来指定函数名。
def _func_(*args,**kwargs):
'''函数说明'''
statements
return Var
- 可以通过
__doc__
方法查看函数说明
#coding:UTF-8
def test_01():
'''this is introduction'''
print "1"
print test_01.__doc__
输出结果:
this is introduction
二、函数的参数
2.1 位置参数
函数根据位置顺序将参数值传入参数
def _testPostion_(a,b):
print "the first var is:",a
print "the second var is:",b
_testPostion_(5,10)
输出结果:
the first var is: 5
the second var is: 10
2.2 默认参数
- 函数部分参数指向默认值,可以不需要在调用时传入该参数函数内就可以使用。
- 位置通常是:必传参数在前,默认参数在后。
- 若默认参数所在的位置传入了参数,则会覆盖默认值
def _test02_(name,sex="boy"):
print name,"and",sex
_test02_("tyson")
_test02_("another tyson","girl")
输出结果:
tyson and boy
another tyson and girl
2.3 关键字参数
最重要的作用是,使用关键字参数调用函数的时候可以不严格按照函数声明时规定的参数的顺序来写。而且函数还能正确识别。
def _test02_(fisrt,second):
print "fisrt var is:",fisrt,"and the second var is:",second
_test02_(second="2",fisrt="1")
输出结果:
fisrt var is: 1 and the second var is: 2
2.4 非关键字可变参数
- 函数可以通过*获取可变数量的参数,并全部放入到元组中,所谓可变就是这些参数可有可无。函数头部分是
def func(*tuple)
。 - 因为参数传入函数后是通过元组存放的,所以没办法辨识参数,因此非关键字可变参数通常用于类似于加法对参数个体顺序不做要求的功能实现。
案例1
def f(*args):
print args
f("tyson")
f("tyson","21")
f("tyson","21","boy")
输出结果
('tyson',)
('tyson', '21')
('tyson', '21', 'boy')
案例2
def sum(*args):
sum = 0
for i in args:
sum+=i
print sum
sum(1)
sum(1,2)
sum(1,2,3)
输出结果
1
3
6
2.5 关键字可变参数
- 函数可以通过获取可变数量的参数,并全部放入到字典中,所谓可变就是这些参数可有可无**。函数头部分是
def func(*dict)
。 - 与非关键字可变参数最大的不同就是关键字可变参数在调用函数时需要为这些额外的参数指定变量名。
def dict(**args):
print args
dict(name="tyson")
dict(name="laowang",age="21")
输出结果:
{'name': 'tyson'}
{'age': '21', 'name': 'laowang'}
2.6 混合参数
- 函数头定义参数列表的时候,可以同时包含位置参数、默认参数、关键字参数、可变参数。
- 参数的顺序是有要求的:位置参数(必备参数)→默认参数→可变参数
def func(x,y=1,*tuple,**dict):
print "x:",x
print "y:",y
print "tuple:",tuple
print "dict:",dict
func(10,20,30,name="tyson")
输出结果:
x: 10
y: 20
tuple: (30,)
dict: {'name': 'tyson'}
三、变量的作用域
3.1 一些基本概念
变量的作用域指的是:变量能够被使用的范围。
3.2 局部变量
在函数内部定义的变量称为局部变量,局部变量只能在函数内被使用,在函数外无法访问该变量。
def _test03_(x,y):
sumTemp = sum(x,y)
_test03_(1,2)
print sumTemp
输出结果:
Traceback (most recent call last):
File "E:/Users/china/PycharmProjects/func_pinginglab/test_01.py", line 4, in <module>
_test03_(1,2)
File "E:/Users/china/PycharmProjects/func_pinginglab/test_01.py", line 2, in _test03_
sumTemp = sum(x,y)
TypeError: 'int' object is not iterable
3.3全局变量
在函数外部定义的变量称为全局变量,全局变量能够被整个程序范围调用。
name = "outsideName"
def _test01_():
print name
_test01_()
输出结果:
outsideName
若有函数内外有同名的变量出现,则首先使用函数内部的变量,但是并不会影响函数外不同名变量的值,这里涉及到了命名空间的问题。
name = "outsideName"
def _test01_():
name = "insideName"
print name
_test01_()
输出结果:
insideName
当然,我们也可以通过关键字global
将局部变量变成全局变量
def _test01_():
global name
name = "insideName"
_test01_()
print name
输出结果:
insideName