In this tutorial, you will learn to write a Python Program To Check Prime Number Using For Loop.
A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself.
In other words, a prime number is a number that is only divisible by 1 and itself.
Examples of prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, and so on.
To understand this program you should have an understanding of the following topics:
Python Program To Check Prime Number Using For Loop
n = int(input("Enter a number: "))
if n < 2:
print(n, "is not a prime number")
else:
is_prime = True
for i in range(2, int(n**0.5)+1):
if n % i == 0:
is_prime = False
break
if is_prime:
print(n, "is a prime number")
else:
print(n, "is not a prime number")
Output
Enter a number: 19
19 is a prime number
In this program, we first prompt the user to enter a number.
If the number is less than 2, we immediately print that it is not prime and exit the program.
If the number is greater than or equal to 2, we initialize a variable is_prime to True and enter a for loop.
The loop will iterate over all the numbers from 2 to the square root of n, checking whether n is divisible by each number.
If it is, we set is_prime to False and break out of the loop.
After the loop, we check whether is_prime is still True.
If it is, then n is a prime number and we print that the number is prime.
Otherwise, we print that the number is not prime.