In this Python lesson, we will practice how to write a program to check if a number is a prime number or not. Examples of prime numbers are, 2, 3, 4, 5, 7, 13, 17, 19 and so on. We will carry out this process using a conditional statement and loop system.
Note: A Prime number is any positive number that is divisible by 1 and itself alone. 1 is neither a prime nor a composite number. A composite number is a positive integer that can be formed by multiplying two smaller positive integers. Equivalently, it is a positive integer that has at least one divisor other than 1 and itself.
Example: Check Prime Number Using a for…else statement
# Request input from user
num = int(input('Enter a number: '))
# prime numbers must be greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print('{0} is not a prime number'.format(num))
break
else:
print('{0} is a prime number'.format(num))
# if input number is less than or equal to 1
else:
print('{0} is not a prime number'.format(num))
Output
Enter a number: 17
17 is a prime number
In the above program, we checked for prime numbers using the for..else statement. We ensured that numbers less than or equal to 1 are not considered prime numbers because prime numbers must be greater than 1 and must not also be a negative numbers.