Program to Check if a Number is Prime in Python
Checking Prime Number
A prime number is a natural number greater than 1 that has no divisors other than 1 and itself.
We will explore different methods to check if a number is prime using Python programming.
Method 1: Using a for Loop
We iterate from 2 to the square root of the number and check for divisibility.
num = int(input("Enter a number: "))
is_prime = True
if num < 2:
is_prime = False
else:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
Output:
Enter a number: 7 7 is a prime number
Method 2: Using a Function
We create a function to check for primality and return the result.
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
num = int(input("Enter a number: "))
if is_prime(num):
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
Output:
Enter a number: 10 10 is not a prime number