Python Program to check whether a number is prime or not

Write a Python program that checks whether a given number is a prime number or not.

Input-Output Examples

plaintext
Example 1:
Input: Enter a number: 11
Output: 11 is a prime number.

Example 2:
Input: Enter a number: 12
Output: 12 is not a prime number.

Algorithm to check whether a number is prime or not

  1. Start
  2. Take input: Prompt the user to enter a number.
  3. Check if the number is prime:
    • A prime number is only divisible by 1 and itself.
    • For any number n:
      • If n <= 1, it is not prime.
      • Check divisibility from 2 to √n:
        • If the number is divisible by any number in this range, it is not prime.
  4. Display the result: Print whether the number is prime or not.
  5. End

Python Program to check whether a number is prime or not

python
# Python program to check if a number is prime

# Take input from the user
num = int(input("Enter a number: "))

# Check if the number is less than or equal to 1 (not prime)
if num > 1:
    # Check for factors from 2 to the square root of the number
    for i in range(2, int(num**0.5) + 1):
        if (num % i) == 0:
            print(f"{num} is not a prime number.")
            break
    else:
        # If no factors found, it is prime
        print(f"{num} is a prime number.")
else:
    print(f"{num} is not a prime number.")

Code Explanation

  1. Taking input from the user:
    The input() function is used to take a number from the user, and it is converted to an integer using int().
  2. Checking if the number is prime:
    A prime number is greater than 1 and divisible only by 1 and itself. The program checks if the number is less than or equal to 1, in which case it is not prime.
    For numbers greater than 1, the program checks if there are any divisors other than 1 and the number itself. It iterates from 2 to the square root of the number (since any factor greater than the square root would already have a corresponding factor smaller than the square root).
    If a divisor is found, the number is not prime, and the loop breaks. Otherwise, it is a prime number.
  3. Displaying the output:
    The print() function is used to display whether the number is prime or not based on the result of the conditionals.

Python

1239

639

Related Articles