Chapter3 函数进阶
2017-12-11 本文已影响0人
木果渣
##basic func
def my_abs(x):
if x >= 0:
return x
else:
return -x
print(my_abs(-99))
##nothing
def nop():
pass
##params check
def new_my_abs(x):
if not isinstance(x, (int, float)):
## raise TypeError('bad operand type')
return
if x >= 0:
return x
else:
return -x
print(new_my_abs('A'))
##default params
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
##return mutiple values
import math
def move(x, y, step, angle = 0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
print(move(100, 100, 30, math.pi / 6))
point = move(100, 100, 30)
print('x: ', point[0], ';y: ', point[1])
##参数numbers接收到的是一个tuple
def calc(*numbers):
sum = 0
for n in numbers:
sum += n * n
return sum
print(calc(1, 2, 3))
print(calc())
##key params
##可变参数在函数调用时自动组装为一个tuple
def person(name, age, **kw):
print('{name:',name, ',age:', age, ',other', kw, '}')
print(person('Alice', 15))
##{name: Bob ,age: 15 ,other {'city': 'Beijing'} }
print(person('Bob', 15, city = 'Beijing'))
##限制关键字参数的名字
def person_2(name, age, *, city):
print(name, age, city)
person_2('HaiYa', 12, city='ShangHai')
##ERROR: person_2('HaiYa', 12, 'ShangHai')
##parictise
##x*y1*y2.....
def product(x, *y):
num = x
for y_x in y:
num *= y_x
print(num)
product(1)
product(1,2,3,4,5,6)
##ax^2 + bx + c = 0
import math
def quadratic(a, b, c):
if a == 0:
raise TypeError('a is 0!')
num = b ** 2 - 4 * a *c
if num < 0:
raise TypeError('b^2 - 4ac < 0')
elif num > 0:
x_1 = (math.sqrt(num) - b)/(a * 2)
x_2 = (- math.sqrt(num) - b)/(a * 2)
return x_1, x_2
return (- b)/(a * 2)
print(quadratic(1, 8, 2))
print(quadratic(1, 2, 1))
print(quadratic(1, 2, 4))