Introduction
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
In other words, a prime number is a number that is only divisible by 1 and itself. For example, 2, 3, 5, 7,
and 11 are prime numbers. Identifying whether a number is prime or not is a common task in mathematics and
computer science.
Objective
The objective of this program is to check whether a given number is prime or not. This is done by verifying
if the number has any divisors other than 1 and itself. The program will take an integer input from the user
and determine if it’s a prime number by checking divisibility.
Python Program Code
def is_prime(number):
# Check if the number is less than or equal to 1
if number <= 1:
return False
# Check for factors from 2 to the square root of the number
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False # If number is divisible by i, it's not prime
return True # If no factors are found, the number is prime
# Input from the user
try:
num = int(input("Enter a number to check if it is prime: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
except ValueError:
print("Please enter a valid integer.")
Program Explanation
The program consists of a function named is_prime()
that accepts a number and checks if it is prime.
The process involves:
- Step 1: Check if the number is less than or equal to 1. Numbers less than or equal to 1 are not prime.
- Step 2: Iterate through numbers starting from 2 up to the square root of the input number.
- Step 3: If the number is divisible by any of the numbers in the range, it is not prime, and the function returns
False
. - Step 4: If no divisors are found, the number is prime, and the function returns
True
.
How to Run the Program
To run the program, follow these steps:
- Ensure that Python is installed on your machine. You can download it from the official website: Python Downloads.
- Copy the Python code provided above into a new file and save it with the extension
.py
(e.g.,prime_checker.py
). - Open a terminal or command prompt.
- Navigate to the directory where the Python file is saved.
- Type the following command and press Enter:
python prime_checker.py
- The program will prompt you to enter a number. Enter any integer to check if it’s prime.