您的位置:首页 > 编程语言 > Python开发

Python学习笔记(5):函数

2010-08-28 15:30 686 查看
在前面我们已经见过一些Python内建函数,比如len和rang。现在我们来看看自定义函数,函数是通过def关键字来定义,后面跟函数名称和圆括号,括号内可以包含参数,该行以冒号结束,接下来是语句块,即函数体。

1. 简单的sayHello函数

def printMax(a, b):
if a >]

3. 局部变量

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

4. 默认参数值


运行结果为:

ha

haha

5. 关键参数

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

6. return语句

def maximum(x, y):
if x >]
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__)
help(printMax)


运行结果为:

5 is maximum.
Prints the maximum of two numbers.
The two values must be integers.
Help on function printMax in module __main__:

printMax(x, y)
Prints the maximum of two numbers.
The two values must be integers.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: