第七章第1讲:python函数的初认知
1. 函数的作用:大大简化了代码的复杂性,提高了代码使用率(简单来说就是,把某段功能的代码给封装起来,供其他地方条用。如pow、range、abs等)
# 斐波契数列 fibs = [0,1] for i in range(8): fibs.append(fibs[-2] + fibs[-1]) print(fibs) # 优化处理 fibs = [0,1] num = int(input("Enter a number:")) for i in range(num): fibs.append(fibs[-2] + fibs[-1]) print(fibs)
2. 函数的定义:
def 函数名(参数1、参数2):
代码块
def fibs(num): fibs = [0,1] for i in range(num): fibs.append(fibs[-2] + fibs[-1]) print(fibs) print(fibs(8)) print(fibs(9)) 结果: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] None [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] None