Friday, December 9, 2022

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')
  # if loop runs completely that means a prime number
    print(num, 'is a prime number')



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!

>>>Return to Python Programs Page

Related Topics

  1. Python Program to Count Occurrences of Each Character in a String
  2. Python Program to Display Fibonacci Series
  3. Python Program to Display Prime Numbers
  4. Python break Statement With Examples
  5. Changing String Case in Python

You may also like-

  1. Python Exception Handling - try,except,finally
  2. Getting Substring in Python String
  3. Constructor in Python - __init__() function
  4. Name Mangling in Python
  5. Java Stream API Tutorial
  6. Difference Between Checked And Unchecked Exceptions in Java
  7. Selection Sort Program in Java
  8. Spring Bean Life Cycle