Discuss / Python / 定义函数总结

### 定义函数总结

Topic source

#### 老夫007

#1 Created at ... [Delete] [Delete and Lock User]

### 空函数

def nop():

    pass


pass语句什么都不做，那有什么用？实际上pass可以用来作为占位符，比如现在还没想好怎么写函数的代码，就可以先放一个pass，让代码能运行起来。

def my_abs(x):

    if not isinstance(x, (int, float)):

        raise TypeError('bad operand type')

    if x >= 0:

        return x

    else:

        return -x


### 返回多个值

import math

def move(x, y, step, angle=0):

    nx = x + step * math.cos(angle)

    ny = y - step * math.sin(angle)

    return nx, ny


nx, ny的值同时返回给函数

import math语句表示导入math包，并允许后续代码引用math包里的sincos等函数。

>>> x, y = move(100, 100, 60, math.pi / 6)

>>> print(x, y)

151.96152422706632 70.0


>>> r = move(100, 100, 60, math.pi / 6)

>>> print(r)

(151.96152422706632, 70.0)


### 小结

#### 威53089

#2 Created at ... [Delete] [Delete and Lock User]

a = input(a='')

b = input(b='')

c = input(c='')

m = b**2 - 4*a*c

if not isinstance(a+b+c, (int, float)):

raise Typeerror('type error')

elif m<0:

print('此方程無解')

else:

x1 = (-b + math.sqrt(m)/(2*a)

x2 = (-b - math.sqrt(m)/(2*a)

return x1, x2

#### 威53089

#3 Created at ... [Delete] [Delete and Lock User]

a = input('a=')

b = input('b=')

c = input('c=')

m = b**2 - 4*a*c

if not isinstance(a+b+c, (int, float)):

raise Typeerror('type error')

elif m<0:

print('此方程無解')

else:

x1 = (-b + math.sqrt(m)/(2*a)

x2 = (-b - math.sqrt(m)/(2*a)

return x1, x2