Python Program to check if a given number is Prime or not
Program
# Python Program to check if a number is prime or not
inputNum = int(input("Enter a number: "))
if inputNum > 1:
for i in range(2,inputNum):
if (inputNum % i) == 0:
print(inputNum,"is not a prime number")
break
else:
print(inputNum,"is a prime number")
else:
print(inputNum,"is not a prime number")
This program determines whether a given number is prime. A prime number is a natural number greater than 1 that is divisible only by 1 and itself.
-
Take User Input
- The program asks the user to enter an integer.
-
Check if Number is Greater than 1
- Since prime numbers start from 2, numbers ≤1 are not prime.
-
Loop to Check Factors
- A
for
loop iterates from 2 toinputNum - 1
. - If
inputNum
is divisible by any number in this range, it is not prime, and the loop breaks.
- A
-
Else Clause for Prime Check
- If the loop completes without finding a factor, the number is prime.
-
Final Output
- The program prints whether the number is prime or not.
Key Takeaways
- Prime numbers have only two factors: 1 and themselves.
- Composite numbers have additional factors.
- The loop stops early if a factor is found, improving efficiency.
Output 1
$ python3 CheckPrimeNumber.py
Enter a number: 245
245 is not a prime number
Output 2
$ python3 CheckPrimeNumber.py
Enter a number: 11
11 is a prime number
Output 3
$ python3 CheckPrimeNumber.py
Enter a number: 1
1 is not a prime number