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.
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.
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
We can create a function to check if a given number is a prime number by testing its divisors.
For example,
is_prime
that takes one parameter number
.False
.for
loop to iterate from 2 to the square root of the number (inclusive).False
.True
.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")
29 is a prime number