Discuss / Python / 交作业

交作业

Topic source

星辰德法

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

    sq = b*b - 4*a*c

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

        raise TypeError("参数输入错误")

    elif sq < 0:

         print("方程无解")

    else:

        x_1 = (-b + math.sqrt(sq))/(2*a)

        x_2 = (-b - math.sqrt(sq))/(2*a)

    return x_1, x_2

Jerry_君轶

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

下面这样好像检测不到变量类型错误

>>> quadratic('c',3,'-c')

Traceback (most recent call last):

  File "<pyshell#5>", line 1, in <module>

    quadratic('c',3,'-c')
    sq=math.sqrt(b**2-4*a*c)
TypeError: can't multiply sequence by non-int of type 'str'

先检测变量类型,再计算sq=math.sqrt(b**2-4*a*c)

# _*_ coding: utf-8 _*_

import math

def quadratic(a, b, c):

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

        raise TypeError('bad operand type')

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

        raise TypeError('bad operand type')

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

        raise TypeError('bad operand type')

    sq=math.sqrt(b**2-4*a*c)

    if sq <0:

        print('this has no solution')

    else:

        x1=float(-b+sq)/(2*a)

        x2=float(-b-sq)/(2*a)

        return (x1,x2)

quadratic('c',3,'-c')

Traceback (most recent call last):

  File "<pyshell#6>", line 1, in <module>

    quadratic('c',3,'-c')

  File "C:/Users/mtk11999/Desktop/My Job/python_test\quadratic_test.py", line 8, in quadratic

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

星辰德法

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

嗯,确实应该分开检测,不过你的if语句可以合并成

if not (isinstance(a,(int, float)) and isinstance(b, (int, float)) and isinstance(c,(int,float))):    raise TypeError('请输入数字.')

dean_92547

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

跑了一下你的代码 ,可以类型检测


  • 1

Reply