In this tutorial, you will learn to write a Python Program To Check Prime Number Using Function.
A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself.
In other words, a prime number is a number that is only divisible by 1 and itself.
Examples of prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, and so on.
To understand this program you should have an understanding of the following topics:
Python Program To Check Prime Number Using Function
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
n = int(input("Enter a number: "))
if is_prime(n):
print(n, "is a prime number")
else:
print(n, "is not a prime number")
Output
Enter a number: 59
59 is a prime number
In this program, we define a function called is_prime().
This function takes a single argument n and returns True if n is prime and False otherwise.
Within the function, we first check whether n is less than 2, since 0 and 1 are not prime.
If n is less than 2, we immediately return False.
We then loop through all the numbers from 2 to the square root of n, checking whether n is divisible by each number.
If it is, we immediately return False.
If we loop through all the numbers without finding a divisor, then n is a prime number and we return True.
In the main part of the program, we prompt the user to enter a number.
Then we call the is_prime() function to check whether it is prime.
If it is, we print that the number is prime.
Otherwise, we print that the number is not prime.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.