## Friday, November 1, 2019

### Python Program to Check Prime Number

In this post we'll see a Python program to check whether the passed number is a prime number or not. This program also shows a use case where for loop with else in Python can be used.

A number is a prime number if it can only be divided either by 1 or by the number itself. So the passed number has to be divided in a loop from 2 till number/2 to check if number is a prime number or not.

You need to start loop from 2 as every number will be divisible by 1.

You only need to run your loop till number/2, as no number is completely divisible by a number more than its half. Reducing the iteration to N/2 makes your program to display prime numbers more efficient.

### Check prime number or not Python program

```def check_prime(num):
for i in range(2, num//2+1):
# if number is completely divisible then it
# it is not a prime number so break out of loop
if num % i == 0:
print(num, 'is not a prime number')
break
# if loop runs completely that means a prime number
else:
print(num, 'is a prime number')

check_prime(13)
check_prime(12)
check_prime(405)
check_prime(101)
```

Output

```13 is a prime number
12 is not a prime number
405 is not a prime number
101 is a prime number
```

That's all for this topic Python Program to Check Prime Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!