Python Program to Check if a Number is Prime

Introduction

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. This tutorial will guide you through creating a Python program that checks whether a given number is prime.

Problem Statement

Create a Python program that:

  • Takes a number as input.
  • Checks if the number is prime.
  • Displays whether the number is prime or not.

Example:

  • Input: 17
  • Output: 17 is a prime number

Solution Steps

  1. Take Input from the User: Use the input() function to get a number from the user.
  2. Convert Input to an Integer: Convert the input string to an integer using int().
  3. Check if the Number is Less Than 2: Since prime numbers are greater than 1, numbers less than 2 are not prime.
  4. Check for Factors: Iterate from 2 to the square root of the number. If the number is divisible by any of these, it is not prime.
  5. Display the Result: Use the print() function to display whether the number is prime.

Python Program

# Python Program to Check if a Number is Prime
# Author: https://www.rameshfadatare.com/

import math

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

# Step 2: Check if the number is less than 2
if num < 2:
    print(f"{num} is not a prime number")
else:
    # Step 3: Check for factors from 2 to the square root of the number
    is_prime = True
    for i in range(2, int(math.sqrt(num)) + 1):
        if num % i == 0:
            is_prime = False
            break

    # Step 4: Display the result
    if is_prime:
        print(f"{num} is a prime number")
    else:
        print(f"{num} is not a prime number")

Explanation

Step 1: Take Input from the User

  • The input() function prompts the user to enter a number. The input is converted to an integer using int().

Step 2: Check if the Number is Less Than 2

  • Since prime numbers are greater than 1, the program first checks if the input number is less than 2. If so, it is not prime.

Step 3: Check for Factors

  • The program iterates from 2 to the square root of the number, checking if the number is divisible by any of these values. If a divisor is found, the number is not prime.

Step 4: Display the Result

  • The print() function is used to display whether the number is prime or not based on the result of the factor check.

Output Example

Example 1:

Enter a number: 17
17 is a prime number

Example 2:

Enter a number: 20
20 is not a prime number

Example 3:

Enter a number: 2
2 is a prime number

Conclusion

This Python program demonstrates how to check whether a number is prime by iterating through possible divisors up to the square root of the number. This method is efficient and helps beginners understand loops, conditionals, and mathematical concepts in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top