for循环中的逐项乘法问题,python

时间:2018-02-14 01:29:07

标签: python loops for-loop multiplication

我正在制定一个程序来计算多个重量和等级列表的加权平均值。我需要创建自定义异常,因为并非所有数据都采用正确的格式。我遇到两个问题,如何创建有用的异常并仍然运行所有列表和两个我的itemize_mult变量抛出错误' a'没有定义。

def weighted_avg(grades, weights): 

    for b in weights:
        if b < 0: 
            (print("For {}".format(weights), "each weight must be 
greater than zero."))
            raise Exception
        if b > 100: 
            (print("For {}".format(weights), "each weight cannot be 
more than 100."))
            raise Exception
        if sum(weights) != 100: 
            (print("For {},".format(weights), "the sum of the weights 
does not equal 100."))
            raise Exception
    for a in grades: 
        if a in grades != b in weights: 
            (print("For {}{}".format(grades, weights, "the number of 
grades must match the number of weights.")))
            raise Exception
        else: 
            itemized_mult = [a*b for grades, weights in zip(grades, 
    weights)]
            combined_weight_grade = sum(itemized_mult)
            output = combined_weight_grade * 100
            print(output)
            print(itemized_mult)

grades1 = [88,99,100,70]
weights1 = [30, 30, 30, 5]

grades2 = [78, 75, 80, 99]
weights2 = [110, 10, -20, 0]

grades3 = [84, 80, 67, 97]
weights3 = [50, 25, 25]

grades4 = [100, 80, 90, 75]
weights4 = [20, 25, 25, 30]

x =(weighted_avg(grades1, weights1))
y =(weighted_avg(grades2, weights2))
z =(weighted_avg(grades3, weights3))
zzz =(weighted_avg(grades4, weights4))

print("List: ", itemized_mult, "Your weighted grade is: ", x)
print("List: ", itemized_mult, "Your weighted grade is: ", y)
print("List: ", itemized_mult, "Your weighted grade is: ", z)
print("List: ", itemized_mult, "Your weighted grade is: ", zzz)

2 个答案:

答案 0 :(得分:1)

引发异常时,可以传入异常消息

raise Exception('Put your useful message here')

您可以像这样创建自定义异常

class MyException(Exception):
    def __init__(self, data, *args, **kwargs):
        super(MyException, self).__init__(*args, **kwargs)
        self.data = data

请注意除了异常消息外,它还接受一些自定义data

def func():
    raise MyException(50, 'This is the exception message')

您可以访问以下属性:

try:
    func()
except MyException as e:
    print(e.message)
    print(e.data)

答案 1 :(得分:0)

以下是清理代码的尝试。为简单起见,我广泛使用了assert,但如果需要,您可以同等raise Exception

def weighted_avg(grades, weights): 

    # overall checks
    assert sum(weights) == 100, "Sum of weights must equal zero: {0}".format(sum(weights))
    assert len(grades) == len(weights), "the number of grades must match the number of weights: {0} vs {1}".format(len(grades), len(weights))

    # specific checks
    for b in weights:    
        assert b >= 0, "Each weight must be greater than zero: {0}".format(b)
        assert b <= 100, "Each weight cannot be more than 100: {0}".format(b)

    # results
    itemized_mult = [a*b for a, b in zip(grades, weights)]
    combined_weight_grade = sum(itemized_mult)
    output = combined_weight_grade / 100

    return itemized_mult, combined_weight_grade, output

grades1, weights1 = [88,99,100,70], [30, 30, 35, 5]
grades2, weights2 = [78, 75, 80, 99], [90, 10, 0, 0]
grades3, weights3 = [84, 80, 67, 97], [50, 25, 25, 0]
grades4, weights4 = [100, 80, 90, 75], [20, 25, 25, 30]

a = weighted_avg(grades1, weights1)
b = weighted_avg(grades2, weights2)
c = weighted_avg(grades3, weights3)
d = weighted_avg(grades4, weights4)

print("List: ", a[0], "Your weighted grade is: ", a[2])
print("List: ", b[0], "Your weighted grade is: ", b[2])
print("List: ", c[0], "Your weighted grade is: ", c[2])
print("List: ", d[0], "Your weighted grade is: ", d[2])