1 定义函数
>>> def myprint():
... print 'hello world'
...
>>> myprint()
hello world
2 函数传递参数
>>> def printMax(a,b):
... if a>b:
... print a
... else:
... print b
...
>>> x=2
>>> y=3
>>> printMax(x,y)
3
3 默认参数值
>>> def printMax(a,b=1):
... if a>b:
... print a
... else:
... print b
...
>>> x=5
>>> printMax(x,y)
5
4 局部变量
>>> def myprint(x):
... print 'x is:', x
... x=2
... print 'x is:', x
...
>>> x=3
>>> myprint(x)
x is: 3
x is: 2
>>> print 'x is :',x
x is : 3
5 全局变量
>>> def myfunc():
... global x
... print 'x is:',x
... x=2
... print 'x is:',x
...
>>> x=3
>>> myfunc()
x is: 3
x is: 2
>>> print 'x is:',x
x is: 2
6 return函数返回值
>>> def printMax(x,y):
... if x>y:
... return x
... else:
... return y
...
>>> print printMax(1,2)
2
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30129545/viewspace-1549387/
,如需转载,请注明出处,否则将追究法律责任。