Check a Prime Number in Python
A prime number is greater than 1 and has no positive divisors other than 1 and itself.
What is Check a Prime Number?
A prime number is greater than 1 and has no positive divisors other than 1 and itself.
Check whether a number is prime with an efficient Python example.
When should you use it?
- Learn Python syntax through a practical example.
- Build a foundation for larger programming problems.
- Test an idea quickly without a local setup.
Example code
main.py
number = 29
is_prime = number > 1
divisor = 2
while divisor * divisor <= number and is_prime:
if number % divisor == 0:
is_prime = False
divisor += 1
print(f"{number} is prime: {is_prime}")
Expected output
29 is prime: True
How it works
Testing divisors only through the square root is sufficient: a larger factor must be paired with a smaller factor already checked.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.