liyihao

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

函数参数检查

#函数异常检查
def test_abs(i):
    if i >= 0:
        return i
    else:
        return -i

test_abs(9)
test_abs(-6)

#这个时候如果传入一个字符串就会有异常报出
#为了让程序运行,提示你这个是参数是错误的,数据类型检查,用函数isinstance()检查
def test_abs(i):
    if not isinstance(i,(int, float)):
        return 'false type'
    if i >= 0:
        return i
    else:
        return -i

'''
isinstance()补充
语法:
isinstance(object, classinfo)
如果参数object 是classinfo 的实例,返回True,反之False

isinstance(1, int)
isinstance(0.5, float)
'''


#函数返回多个值
#在summer那个地方我记得也用过,但是好像没有引入math这个模块
#回顾了一下,当时用的是一个list 的两个索引,更新索引完成list的更新,所以summer的位置也就移动了
import math

def move(x, y, step, angle=0):
    x1 = x + step * math.cos(angle)
    y1 = y + step + math.sin(angle)
    return (x1, y1)

x, y = move(5,9,10)
print (x, y)

#这里直接用move()
move(5,9,10)
#(15.0, 19.0)
#返回是个tuple


'''
练习
请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:
ax2 + bx + c = 0
的两个解。
提示:计算平方根可以调用math.sqrt()函数:
'''

'''
def quadratic(a, b, c):
    ax2 + bx + c = 0
    x1 + x2 = -a/b
    x1 * x2 = c/a
    return x1, x2
'''
#这道题解题思路有问题,以为先返回方程,再去求根

import math

def quadratic(a, b, c):
    if not isinstance(a, (int, float)):
        return 'a is false type'
    if not isinstance(b, (int, float)):
        return 'b is false type'
    if not isinstance(c, (int, float)):
        return 'c is false type'
    if a==0:
        return r'a不能=0'
    d = b*b - 4*a*c
    if d > 0:
        x1 = (-b + math.sqrt(d))/(2*a)
        x2 = (-b - math.sqrt(d))/(2*a)
        print (r'此方程有2个根')
        return x1, x2
    if d == 0:
        x1 = (-b + math.sqrt(d))/(2*a)
        x2 = (-b - math.sqrt(d))/(2*a)
        print (r'此方程有1个根')
        return x1, x2
    if d < 0:
        return r'无解'


#加入了参数检查

  

posted on 2017-12-18 15:41  liyihao  阅读(181)  评论(0)    收藏  举报