A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
# Taking input from the user
number = int(input("Enter a number to check if it's prime: "))
if is_prime(number):
print(number, "is a prime number")
else:
print(number, "is not a prime number")
Enter a number to check if it's prime: 17
17 is a prime number
The function is_prime(num)
takes an integer num
as input and returns True
if the number is prime and False
otherwise.
It first checks if num
is less than or equal to 1, in which case it returns False
as numbers less than or equal to 1 are not prime.
Then, it iterates through the numbers from 2 to the square root of num
. If any of these numbers evenly divide num
, it returns False
, indicating that num
is not prime. Otherwise, it returns True
.
The example usage section demonstrates how to take input from the user and print whether the entered number is prime or not.