python-函数的定义与调用

求斐波那契数列的前n项:

def febs(n):
    res=[1,1]
    for i in range(n-2):
        res.append(res[-2]+res[-1])
    return res
print(febs(5))

output: [1, 1, 2, 3, 5]

函数必须先定义再调用:

  • 下面这个例子是错误的
print(f(3))

def f(x):
    y=x**2
    return y

output:
Traceback (most recent call last):
  File "wsx.py", line 1, in <module>
    print(f(3))
NameError: name 'f' is not defined

  • 修改后
def f(x):
    y=x**2
    return y

print(f(3))

output:
9

lambda 函数

  • lambda可以用来编写简单的函数
g=lambda x,y,z: x+2*y+z**2
print(g(1,2,3))

output:
14
  • 定义一个函数y=sin(x)+1:
import math
y=lambda x: math.sin(x)+1
print(y(math.pi/6))

output:
1.5

你可能感兴趣的:(python笔记)