1st: I want to write a function "div" that takes two numbers as parameters and returns the quotient of the first number divided by the second number. and need to use a try-except statement to do the division. And in case of division by 0, use the except clause to return a special float value 'nan' (not a number).
2nd: After that, I need to design a number of test cases to test the function (unit test) with the aim of identifying all possible errors of the function. For each test, specify both the input and the expected output. For each test case, carry out the test and compare the actual test result with the expected result..
I'm did 1st point-
def div(a, b):
try:
return a / b
except ZeroDivisionError:
return float('nan')
I'm stuck on the 2nd point called "unit testing"
Can someone please help me?
-
Show us what you have tried so far.Klaus D.– Klaus D.2025年05月10日 06:17:46 +00:00Commented May 10, 2025 at 6:17
-
I'm did 1st point- def div(a, b): try: return a / b except ZeroDivisionError: return float('nan') # Unit Tests ? I'm stuck on the 2nd point called "unit testing"Kasun98– Kasun982025年05月10日 07:57:01 +00:00Commented May 10, 2025 at 7:57
-
It's better to edit your original question to include your code attempt as @KlausD. asked, rather than posting it in a comment. That makes it easier for others to follow and provide a complete answer.Achraf Ahmed Belkhiria– Achraf Ahmed Belkhiria2025年05月10日 09:15:46 +00:00Commented May 10, 2025 at 9:15
-
What, specifically, are you stuck on regarding unit testing?ndc85430– ndc854302025年05月16日 16:23:28 +00:00Commented May 16, 2025 at 16:23
2 Answers 2
how about:
class TestDivFunction(unittest.TestCase):
def test_division(self):
self.assertEqual(div(10, 2), 5)
self.assertEqual(div(-10, 2), -5)
self.assertEqual(div(0, 1), 0)
def test_division_by_zero(self):
self.assertTrue(math.isnan(div(10, 0)))
1 Comment
I think that your function div is perfect to answer to your 1st point. I suppose that your function is saved in a file called div_function.py. So the content of the file div_function.py is exactly your code:
def div(a, b):
try:
return a / b
except ZeroDivisionError:
return float('nan')
For the 2nd point you can use the Python unittest module and create some tests function which will validate your code.
An example of a file able to execute these tests is the following:
import math
import unittest
from div_function import div
class TestDiv(unittest.TestCase):
# test 1: 20:2 == 10
def test_div_01(self):
self.assertEqual(10, div(20, 2))
# test 2: 11:2 == 5.5
def test_div_02(self):
self.assertEqual(5.5, div(11, 2))
# test 3: 10:3 (with 3 decimal) == 3.333
def test_div_03(self):
self.assertEqual(3.333, round(div(10, 3),3))
# test of 'nan': 10:0 is not possible
def test_div_04(self):
self.assertTrue(math.isnan(div(10, 0)))
if __name__ == '__main__':
unittest.main()
See the comments added to every tests for some other details.
Comments
Explore related questions
See similar questions with these tags.