How to Write a Python Program to Check for Prime Numbers?

Estimated read time 2 min read

To check if a given number is prime, you can write a Python program using the following steps:

  1. Get the input number from the user.
  2. Check if the input number is less than 2. If it is, print that it is not a prime number and stop the program.
  3. Iterate from 2 to the square root of the input number (inclusive) using a for loop.
  4. Check if the input number is divisible by any number in the iteration.
    • If it is divisible, print that it is not a prime number and stop the program.
    • If none of the numbers divide the input number, it is a prime number.
  5. If the loop completes without finding a divisor, print that the input number is a prime number.

Here’s the complete code for the program:

import math

# Step 1: Get input number from the user
num = int(input("Enter a number: "))

# Step 2: Check if the number is less than 2
if num < 2:
    print(num, "is not a prime number.")
    exit()

# Step 3: Iterate from 2 to the square root of the number
for i in range(2, int(math.sqrt(num)) + 1):
    # Step 4: Check if the number is divisible by i
    if num % i == 0:
        print(num, "is not a prime number.")
        exit()

# Step 5: The number is prime
print(num, "is a prime number.")

Now you can run the program, enter a number, and it will tell you whether the number is prime or not.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply