Technical Roadmap

Python Prime Number Program

The Logicoria Tip

A Prime Number is like an "Exclusive Club" with only two members: 1 and Itself. If any other number (like 2, 3, or 5) can get inside, the club is no longer Prime.

Before making a program, let's understand what a prime number is.

What is a Prime Number?

A natural number that is greater than one and has only two factors: 1 and itself.

How to know a prime number?

  • It must be a whole number greater than 0.
  • It must be greater than 1 . 1 is neither prime nor composite.
  • It is only divisible by 1 and itself.

How to check for Prime

  • We will use if with the modulo % operator to check if a number is completely divisible by another. If it gives a remainder of 0, then it is divisible.
  • We will use the range function to iterate from 2 because 1 is not prime, so we don't need to check divisibility for it.
  • At last, if we find even one number that is dividing the number completely other than 1 or itself, we know it's not prime, so we'll use break to exit the loop.
PYTHON
num = int(input("Enter a number: "))
count = 0

# Loop to find how many numbers divide 'num' perfectly
for i in range(1, num + 1):
    if (num % i) == 0:
        count = count + 1

# checking count
if count == 2:
    print(f"{num} is a prime number.")
else:
    print(f"{num} is not a prime number.")

Output

Enter a number: 20
20 is not a prime number.

Explanation:

  • 1. First, we declare a variable num and take a no as input from user in it.
  • Let's take input as 20
  • In second line we declare a count variable with initial value 0. We will use it to find the count of numbers that complely divides our input number.
  • 2. Then we used a for loop to iterate from 1 to num+1. We put second parameter in range function as num+1 not num because by default th erange functions exckludes th elst value.
  • 3.then we used if condition to check all numbers whihc divides out input no completly and hgives 0 as remainder. inside if we are icraeding count by 1 evrytime our if block executes.
  • at last when th eloop chceks ll number from 1 to 20 it stops ./li>
  • 5. In next line we use another if to check c ount. here if our count is excatly 2 we say its prime. othwrise else blcok executes and we get no