python学习笔记之函数(方法)
2014-06-06 16:19
701 查看
def func(x): print 'x is', x x = 2 print 'Changed local x to', x x = 50 func(x) print 'x is still', x
结果:
x is 50 Changed local x to 2 x is still 50
在函数内改变全局变量的值(global)
def func(): global x print 'x is', x x = 2 print 'Changed local x to', x x = 50 func() print 'Value of x is', x
结果:
x is 50 Changed global x to 2 Value of x is 2
默认参数
def say(message, times = 1): print message * times say('Hello') say('World', 5)
结果:
Hello WorldWorldWorldWorldWorld
关键参数
def func(a, b=5, c=10): print 'a is', a, 'and b is', b, 'and c is', c func(3, 7) func(25, c=24) func(c=50, a=100)
结果:
a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50
函数的return
def maximum(x, y): if x > y: return x else: return y print maximum(2, 3)
结果:3
空语句块pass
def someFunction(): pass
DocStrings
读取函数的doc注释信息,DocStrings也适用于模块和类
文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。
def printMax(x, y): '''Descript: this is printMax function descript end.''' x = int(x) # convert to integers, if possible y = int(y) if x > y: print x, 'is maximum' else: print y, 'is maximum' printMax(3, 5) print printMax.__doc__ print '---' help(printMax)
结果
5 is maximum Descript: this is printMax function descript end. --- Help on function printMax in module __main__: printMax(x, y) Descript: this is printMax function descript end.
相关文章推荐
- Python学习笔记(三):随机生成函数方法
- Python 学习笔记 - 9.函数(Function)
- Python函数学习笔记
- C#学习笔记------Visual C#常用函数和方法
- python学习笔记--探索函数
- python简明教程学习笔记2--函数
- Python学习笔记三(Try-cacth&with方法)
- [ADO学习笔记] RecordSet对象的函数与方法
- javascript学习笔记—DOM常用API、属性、方法、函数
- Python学习笔记整理(十二)Python的函数
- python学习笔记17-常用函数总结整理
- Python学习笔记-XML大文件的XSD验证方法
- Python 学习笔记:需要仔细阅读一个函数
- Python学习笔记(三)函数初识和内置函数
- C#2005 .NET3.0高级编程学习笔记————类和结构,类的数据成员,类的函数成员(方法、属性)
- Python学习笔记(函数)
- Python学习笔记九:列表(1)--列表元素介绍及创建方法
- Python学习笔记(5):函数
- python学习笔记8-函数整理
- 2.关于结构体以及结构体数组作为函数入口参数的方法(学习笔记)