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
原文地址:https://www.cnblogs.com/ling07/p/11173855.html
时间: 2024-10-02 00:58:24