Discuss / Python / def语句定义函数,空函数,参数检查,返回多值函数实现(tuple而已)

def语句定义函数,空函数,参数检查,返回多值函数实现(tuple而已)

Topic source
# coding=utf-8

import math

a = int(input('请输入a:'))
b = int(input('请输入b:'))
c = int(input('请输入c:'))

def sqrt(a,b,c):
    if not isinstance(a, (int, float)) or not isinstance(b, (int, float)) or not isinstance(c, (int, float)):
        raise TypeError('bad operand type')
    if a == 0:
        raise TypeError('a不能为0')
    d = math.pow(b, 2) - 4 * a * c
    if d < 0:
        print("无实数根")
    else:
        root1 = (-b + math.sqrt(d)) / (2 * a)
        root2 = (-b - math.sqrt(d)) / (2 * a)
        print("root1=", root1)
        print("root2=", root2)

sqrt(a,b,c)

感觉这里有点问题 a = int(input('请输入a:')) b = int(input('请输入b:')) c = int(input('请输入c:')) 如果这样已经强制转换了,如果输入的不能转换为int就已经报错了,后面函数里面在判断没有意义,另外你转换成int类型,那如果用户输入的是float咋办,虽然不报错,但是结果已经不一样了


  • 1

Reply