chengxianju 发表于 2013-2-7 00:41:18

python函数

刚接触python,感觉语法简洁,大方,小巧,玲珑
官方定义(google翻译):
 
Python是一种编程语言,可以让你的工作更迅速,更有效地融入你的系统。你可以学习如何使用Python和看到几乎眼前利益生产率和降低维护成本。 
 
 
 
python函数接触,定义用def
 
 
 
1.python函数
>>> def test(x) :
 x=x+1
 return x
>>> test(9)
10
>>>
函数体一定要注意缩进,还有冒号

>>> def test():
 sum=1+1
 
>>> a=test()
>>> a
>>>
>>> print a
None
>>>
没有return语句,返回None
 

>>> def test(x,y):
 print x,'--',y
 
>>> test(3,6)
3 -- 6
>>> def test(y=5,x=9):
 print x,'---',y
 
>>> test()
9 --- 5
>>> test(45)
9 --- 45
>>>
python支持缺省参数
 
python变量作用域
>>> globalInt =   9
>>> def test():
 localInt=10
 return globalInt+localInt
>>> print test()
19
>>> print globalInt
9
>>> print localInt
Traceback (most recent call last):
  File "<pyshell#55>", line 1, in <module>
    print localInt
NameError: name 'localInt' is not defined
>>>

>>> g=90
>>> def test():
 g=89
 return 'g=',g
>>> test
<function test at 0x011DF970>
>>> test()
('g=', 89)
>>>
python中global和php中一样
>>> g=90
>>> def test():
 global g
 g='this is global var'
 return g
>>> print test()
this is global var
>>>
页: [1]
查看完整版本: python函数