第7章 函数
通过def关键字定义。
定义函数
- #!/usb/bin/python
- #Filename function.py
- def sayHello():
- print 'Hello World'
- sayHello()
$python function.py
Hello world
- #!/usr/bin/python
- #Filename func_param.py
- def printMax(a, b): # 函数的形参 a 和 b
- if a > b:
- print a, 'is maximum'
- else:
- print b, 'is maximum'
- printMax(3, 4)
- x = 5
- y = 7
- printMax(x, y)
$python func_param.py
4 is maximum
7 is maximum
- #!/usb/bin/python
- #Filename func_local.py
- def func(x):
- print 'x is', x
- x = 2
- print 'Changed local x to', x
- x = 50
- func(x)
- print 'x is still', x
$python func_local.py
x is 50
Changed local x to 2
x is still 50
- #!/usr/bin/python
- #Filename func_global.py
- 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
$python func_global.py
x is 50
Changed global x to 2
Value of x is 2
- #!/usr/bin/python
- #Filename func_default.py
- def say(message, times = 1):
- print message * times
- say('Hello')
- say('World', 5)
$python func_default.py
Hello
WorldWorldWorldWorldWorld
- #!/usr/bin/python
- #Filename func_key.py
- 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)
$python func_key.py
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
- #!/usr/bin/python
- #Filename func_return.py
- def maximum(x, y):
- if x > y:
- return x #注:没有返回值等价于return None
- else: #每个函数结尾暗含return None
- return y
- print maximum(2, 3) #从此可以看出函数没有返回任何对象
$python func_return.py
3
- def someFunction():
- pass #pass语句在Python中表示一个空的语句块
- #!/usr/bin/python
- #Filename func_doc_strings.py
- def printMax(x, y):
- '''''Prints the maximum of two numbers.
- The two values must be integers.''' #文档字符串惯例是一个多行字符串,它的首行以大写字母开始,句号结尾;第二行是空行,从第三行开始是详细描述
- x = int(x)
- y = int(y)
- if x > y:
- print x, 'is maximum'
- else:
- print y, 'is maximum'
- printMax(3,5)
- print printMax.__doc__ #( __doc__ ,调用printMax函数文档字符串属性。注意双下划线)
本文出自 “今天的收成” 博客,请务必保留此出处http://managers.blog.51cto.com/107937/1108023