Python浮点除法纽约零错误

Python Float division ny zero Error

Python浮点数除以零错误。我找不到任何错误。任何人都可以修复它吗?我在 Odoo 版本 10 中使用此代码。我尝试了一些其他方法,但它不起作用。希望它也可能对某人有所帮助。

class etq_results(models.Model):

    _name = "etq.result"
    _description = "Exam Result"

    exam_id = fields.Many2one('etq.exam', string="Exam", readonly=True)
    user_id = fields.Many2one('student.student',"Exam candidate / Student", translate=True)
    score = fields.Float(string="Score", compute="_compute_score", store=True)
    results = fields.One2many('etq.result.question', 'result_id', string="Results", readonly=True)
    token = fields.Char(string="Token")
    state = fields.Selection([('incomplete','Incomplete'), ('complete','Complete')], string="State")

    @api.one
    @api.depends('results')
    def _compute_score(self):
        num_questions = self.env['etq.result.question'].search_count([('result_id', '=', self.id)])
        correct_questions = self.env['etq.result.question'].search_count([('result_id', '=', self.id), ('correct', '=', True)])
        # raise UserError(_(float(num_questions)))
        if float(num_questions) and float(correct_questions) is None:
            self.score = 0.0
        else:
            self.score = float(correct_questions) + "/" + float(num_questions) + " " + (float(correct_questions) / float(num_questions)) * 100.0 + "%"

我想你想用你的 if 测试做什么是这样的:

if not float(num_questions):

换句话说,如果 float(num_questions) 为零——因此是错误的——你想跳过其中包含 / float(num_questions) 的代码,这是非法的。 correct_questions 在这里是什么并不重要。毕竟,除以 0 / 3 不是除以零;而是除以零。没关系。

你实际写的是一个完全不同的测试:

if float(num_questions) and float(correct_questions) is None:

您正在测试 float(num_questions) 是否为真——与您想要的完全相反——还有 float(correct_questions) is None——永远不可能为真,因为只有 None is None。所以,你总是会点击 else。因此,如果 num_questions 值为零,您将除以零。

而您尝试的修复并没有太大区别:

if float(num_questions) or float(correct_questions) == 0.0:

您正在测试 num_questions 是否为真,这仍然与您想要的相反,或者 correct_questions 为 0。第一部分可能为假的唯一方法是如果有没有问题——在这种情况下没有正确的问题,所以第二部分为真。所以现在,你总是点击 if 并且总是显示 0.0.


如果你过了那个,你还有另一个问题:

self.score = float(correct_questions) + "/" + float(num_questions) + " " + (float(correct_questions) / float(num_questions)) * 100.0 + "%"

您正在尝试添加浮点数和字符串。那是非法的。您可能需要的是字符串格式,如下所示:

pct = float(correct_questions) / float(num_questions) * 100.0
self.score = f"{correct_questions}/{num_questions} {pct}%"

或者,如果您使用的是旧版本 Python:

self.score = "{}/{} {}%".format(correct_questions, num_questions, pct)

您可能希望 if 子句匹配相同的格式,而不是只显示 0.0?

self.score = "0.0/0.0 0.0%"

虽然我们正在这样做,但一遍又一遍地调用 float(correct_questions) 会使您的代码更难阅读(并且会慢一点,但这可能无关紧要)。为什么不只调用一次并存储结果?

此外,这些真的是浮点数而不是整数吗?来自数据库计数操作的称为 num_questions 的东西肯定会是一个整数,对吧?

所以,把它们放在一起:

num_questions = int(self.env['etq.result.question'].search_count([('result_id', '=', self.id)]))
correct_questions = int(self.env['etq.result.question'].search_count([('result_id', '=', self.id), ('correct', '=', True)]))

pct = 0.0
if num_questions:
    pct = correct_questions * 100.0 / num_questions
self.score = f"{correct_questions}/{num_questions} {pct}%"