Learn about Prime Number in Python using Function in the below code example. Also, refer to the comments in the code snippet to get a detailed view about what’s actually happening.
A prime number is a positive integer greater than 1 that can be divided by 1 and itself.
Contents
Prime Number in Python using Function
The below code snippet checks whether the given number is a prime or not. The function isPrime()
returns True if the given number is a prime number else returns False.
Program:
# Python program to check if a number is prime or not
#user-defined function
def isPrime(num):
if num > 1:
for i in range(2, num//2):
if (num % i) == 0:
return False
break
else:
return True
else:
return False
# input number
num = int(input('Enter a number: '))
# calling function and display result
if(isPrime(num)):
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Output:
Enter a number: 5
5 is a prime number
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Code : Prime Number Program in Python using While Loop