Check a prime number in Python
Test divisors up to the square root of the number. Press Run to try it, then change the code and run it again.
main.py
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
n = int(input("Enter a number: "))
print(n, "is a prime number" if is_prime(n) else "is not a prime number")
Output
Press Run to see the output.
More Python examples
- Hello, World · Print a line of text.
- Reverse a string · Use slicing with a step of -1.
- Fibonacci series · Print the first n Fibonacci numbers with a generator.
- Add numbers from input · Read several numbers on one line and add them up.
- Count words with a dictionary · Count how often each word appears.