D
D
Demigodd2018-05-26 10:31:08
Python
Demigodd, 2018-05-26 10:31:08

Python Unittest How to check if a number is Integer and Not negative?

Let's say I have a function

def isPrime(n):
    '''Check if integer n is a prime'''
    n = abs(int(n))
    if n < 2:
        return False
    if n == 2: 
        return True    
    if not n & 1: 
        return False
    for x in range(3, n):
        if n % x == 0:
            return False
    return True

Which takes n a number, and if that number is prime then returns True or False if not.
Here's an example Unittest code.
import unittest

class PrimeUnityTest(unittest.TestCase):
    def test_Int(self):
        self.assertTrue(isPrime(5.8), 'N is not Integer!')
    def test_neg(self)
        self.assertTrue(isPrime(-2), 'N is Negative Number!')

How to correctly check whether the type of a number is N → Int and not Float, and check the number for negative, what assert methods can be used to do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2018-05-26
@Demigodd

if n > 0 and not n % 2

R
Ruslan., 2018-05-26
@LaRN

Sorry for the offtopic, but you can speed up the check if you replace
for x in range(3, n): with
for
x in range(3, round(sqrt(n))):

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question