def isPrime(n):
'''
checking n is positive integer or not
'''
val = int(n)
if(val<1):
return False
return True
The purpose of mine is to check if a number is a prime or not. So I think through checking whether the number is a positive integer or not, then will make it to be a test for prime number,
CodePudding user response:
The question is not particular clear so here is my best guess of a solution along with tests:
def is_positive(n):
'''
checking n is positive integer or not
'''
return isinstance(n, int) and n > 0
for i in [-1, 0, 1, '-1', '1', 1.1]:
print(f"{i} {is_positive(i)} {type(i)}")
which prints:
-1 False <class 'int'>
0 False <class 'int'>
1 True <class 'int'>
-1 False <class 'str'>
1 False <class 'str'>
1.1 False <class 'float'>
And here is an implementation of is_prime() along with suitable tests:
def is_prime(n):
if not isinstance(n, int) or n <= 1:
return False
for i in range(1, int(n/2)):
if not n % i:
return False
return True
for i in [-2, 0, 1, 2, 3, 4, 8.9]:
print(f"{i} {is_prime(i)}")
which returns:
-2 False
0 False
1 False
2 True
3 True
4 False
8.9 False
CodePudding user response:
To check that something is a whole number, you can for example do (x-int(x)) == 0
.
Unless you want to make sure it's an int
, ie the Python type. Which is done with isinstance(int, x)
.
I would probably check if something is a positive integer in this way:
def isPositiveInt(num):
if (num - int(num)) != 0:
return False
if num < 1:
return False
return True