Learn Programming and technology with ease @ developerpublish.com

HomePythonPython Program to Check Prime Number

# Python Program to Check Prime Number

In this Python program, we will create a Python script to check whether a given number is prime or not. A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself.

## Problem Statement

Given an input number, we need to determine whether it is a prime number or not.

## Python Program to Check Prime Number

```def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

# Main program
number = int(input("Enter a number: "))

if is_prime(number):
print(number, "is a prime number.")
else:
print(number, "is not a prime number.")```

## How it works

1. The program defines a function `is_prime(num)` that takes a number as input and checks if it is prime or not.
2. If the given number `num` is less than or equal to 1, the function returns `False` as numbers less than or equal to 1 are not prime.
3. The function then loops from 2 to the square root of `num` (inclusive) and checks if `num` is divisible by any of these numbers.
4. If `num` is divisible by any number in the range, it is not a prime number, and the function returns `False`.
5. If no factors are found, the function returns `True`, indicating that the number is prime.
6. In the main program, the user is prompted to enter a number. The input is stored in the `number` variable.
7. The program then calls the `is_prime` function with the `number` as an argument.
8. If the returned value is `True`, it means the number is prime, and a corresponding message is printed.
9. If the returned value is `False`, it means the number is not prime, and a different message is printed.

## Input / output

### You May Also Like

#### Python Program to Remove Duplicates from a Linked List

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...

#### Python Program to Solve the Celebrity Problem

This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...

#### Python Program to Solve n-Queen Problem with Recursion

This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...