Python: Check Prime Number

1. Introduction

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, if a number is prime, it cannot be divided evenly by any other number than 1 and itself. Understanding and checking for prime numbers is a foundational topic in number theory and has applications in areas such as cryptography.

In this blog post, we will learn how to write a Python program to check if a number is a prime number.

2. Program Overview

The Python program that we'll create will follow these steps:

1. Take an input number from the user.

2. Check if the number is less than 2. If yes, it's not prime.

3. For numbers 2 and above, use a loop to check for factors other than 1 and the number itself.

4. Display whether the number is prime or not.

3. Code Program

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

# Initialize a flag variable
is_prime = True

# Prime numbers are greater than 1
if num > 1:
    # Check for factors
    for i in range(2, int(num**0.5)+1):
        if (num % i) == 0:
            is_prime = False
            break
else:
    is_prime = False

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

Output:

Enter a number: 29
29 is a prime number

4. Step By Step Explanation

1. We begin by taking input from the user. The input() function returns a string, so we convert this to an int.

2. We initialize a boolean variable is_prime to True. This variable will help us determine the primality of our input number.

3. If the number is greater than 1, we proceed to check for factors. To optimize the process, we only iterate up to the square root of the number (num0.5) because a larger factor of the number must be a multiple of a smaller factor that has been already checked.

4. If we find any number between 2 and num that divides num evenly (num % i == 0), then num is not a prime number.

5. If the number is less than 2 or if a factor is found, is_prime is set to False.

6. Finally, we use the value of is_prime to display the appropriate message to the user.

Comments