Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Examples
  3. Prime Number Checker

Number Programs · Python example

Prime Number Checker

Test divisibility up to the square root of a number for an efficient prime check.

Open the compilerAll examples
intermediateprime numbersloopsbreak

A prime number has exactly two positive divisors: 1 and itself. Checking possible divisors only up to the square root is enough.

example.py
number = 97

if number < 2:
    is_prime = False
else:
    is_prime = True
    for divisor in range(2, int(number ** 0.5) + 1):
        if number % divisor == 0:
            is_prime = False
            break

print(f"{number} is prime" if is_prime else f"{number} is not prime")

How the code works

  • The loop tests divisors from 2 through 9, since √97 is about 9.85.
  • None divide 97, so is_prime remains True.
  • A conditional expression chooses the message.

Key ideas

  • Numbers below 2 are not prime.
  • If n = a × b and both factors are greater than √n, their product exceeds n.
  • break stops the loop as soon as a divisor is found.

Try changing it

  • Print all prime numbers below 100 with a nested loop.
  • Use a function that returns a boolean.
  • Skip even divisors after checking 2.

Related examples

beginner

Even or Odd Checker

Use the modulo operator and an if-else statement to classify an integer.

beginner

Calculate a Factorial

Multiply numbers in a loop to compute n! with a loop.

Previous exampleFibonacci SeriesNext exampleReverse a Number

Expected output

97 is prime

Output is compared after trimming trailing whitespace on each line. Run the code to see it produced by CPython in your browser.

Practice next

Apply the same idea with automatic tests or browse a guided project.

ExercisesProjects