Python Program to Check Prime Numbers – 2023

Hey guys, in this blog we will see a Python Program to Check Prime Numbers.

Code

# Python Program to Check Prime Numbers

num = int(input("Enter a positive number: "))

# define a flag variable
flag = False

# prime numbers are greater than 1
if num > 1:
    # check for factors
    for i in range(2, num):
        if (num % i) == 0:
            # if factor is found, set flag to True
            flag = True
            # break out of loop
            break

# check if flag is True
if flag:
    print(num, "is not a prime number")
else:
    print(num, "is a prime number")

Output

Enter a positive number: 23
23 is a prime number
Enter a positive number: 12
12 is not a prime number
Enter a positive number: 11
11 is a prime number
  • Here we are running a for-loop from 2 to the number itself and checking if we found any factor of the number. We are finding factors by using the mod operator(%).
  • If we get any factor, we will set the flag=True which means it is not a prime number.
  • Else it is a prime number.

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 521

Leave a Reply

Your email address will not be published. Required fields are marked *