- 函数的工作原理
函数就像一个程序内的小程序,它的主要目的是将需要多次执行的代码放在一起。
def hello():
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
hello()
hello()
hello()
上面的程序调用了3次 hello() 函数,所以函数中的代码执行了次。
如果没有函数定义,可能每次都需要复制粘贴这些代码,像下面这样。
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
一般来说,我们总是希望避免复制代码,因为如果要更新代码,就必须要修改所有复制的代码。
消除重复能够使程序更短、更易读、更容易更新。
- def 语句和参数
调用 print() 或 len() 函数时,会传入一些值,放在括号之间,这些值称为“参数”。
也可以自己定义接收参数的函数。
def hello(name):
print('Hello ' + name)
hello('Alice')
hello('Bob')
hello() 函数定义中,有一个名为 name 的变元。“变元”是一个变量,当函数被调用时,参数就存放在变元中。hello() 函数第一次被调用时,使用的参数是‘Alice’,程序执行进入 hello() 函数,变量 name 自动设为 ‘Alice’,就是之后print()语句打印出来的内容。
- 注意:保存在变元中的值,在函数返回后就丢失了。
如果在 hello(‘Bob’) 之后添加 print(name),程序会报错,因为没有名为 name 的变量。
在函数调用 hello(‘Bob’) 返回后,这个变量被销毁了,所以 print(name) 会引用一个不存在的变量 name.
(End)