Python学习笔记(5):函数

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

1. 简单的sayHello函数

def sayHello():
    print("Hello world!")

#调用函数
sayHello()

2. 带形参函数

def printMax(a, b):
    if a > b:
        print(a, "is maximum.")
    else:
        print(b, "is maximum.")

printMax(3, 4)

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. 默认参数值

def say(message, times = 1):
    print(message * times)

say("ha")
say("ha", 2)

运行结果为:

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 > y:
        return x
    else:
        return y

print(maximum(2, 3))

7. 文档字符串DocStrings

Python有一个奇妙的特性,就是文档字符串(DocStrings),它的主要作用就是帮助你的程序文档更加简单易懂。

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.

原文地址:https://www.cnblogs.com/known/p/1811091.html