A prime number is a number greater than 1 that has only two factors: 1 and itself.
Examples of prime numbers are 2, 3, 5, 7, 11, 13, 17, and 19.
In Python, we can use a function to check whether a number is prime.
Python Program
def is_prime(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
number = int(input("Enter a number: "))
if is_prime(number):
print(number, "is a prime number")
else:
print(number, "is not a prime number")
How It Works
1. Create a function
def is_prime(n):
The function is_prime() receives a number n.
2. Check numbers less than 2
if n < 2:
return False
Numbers like 0 and 1 are not prime numbers.
3. Check for factors
for i in range(2, n):
The loop checks numbers from 2 up to n-1.
4. Use the modulo operator
if n % i == 0:
return False
If n is exactly divisible by any number other than 1 and itself, it is not prime.
5. Return True
return True
If no factor is found, the number is prime.
Example Output
Enter a number: 17
17 is a prime number
Another example:
Enter a number: 20
20 is not a prime number
Conclusion
Using a function makes the prime number program simple, reusable, and easy to understand. The same is_prime() function can also be used when checking many numbers in a program.
Top comments (0)