Python Tutorials

Python Programs

Python Check Prime Number


Python Check Prime Number

In this tutorial, we will learn how to check if a number is a prime number in Python. We will cover the basic logic and conditions required to determine if a number is prime.


What is a Prime Number

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. This means that a prime number cannot be formed by multiplying two smaller natural numbers.


Syntax

The syntax to check if a number is prime in Python is:

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


Checking if a number is a prime number

We can create a function to check if a given number is a prime number by testing its divisors.

For example,

  1. Define a function named is_prime that takes one parameter number.
  2. Check if the number is less than or equal to 1. If true, return False.
  3. Use a for loop to iterate from 2 to the square root of the number (inclusive).
  4. Check if the number is divisible by any of the values in the loop. If true, return False.
  5. If the loop completes without finding any divisors, return True.
  6. Call the function with a sample number and print the result.

Python Program

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

# Check if 29 is a prime number
result = is_prime(29)

# Print the result
if result:
    print("29 is a prime number")
else:
    print("29 is not a prime number")

Output

29 is a prime number