Python Program for checking if a Number is Prime or not
In this tutorial, we will discuss python program for checking if a number is Prime or not.
Before going to the program first, let us understand what is a Prime Number.
Prime Number
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, 11, etc., are prime numbers.
Related: Python Program for Binary Search
Program code for checking if a number is prime or not in Python
# Prime Number Checker in Python def is_prime(num): if num <= 1: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True number = int(input("Enter a number: ")) if is_prime(number): print(f"{number} is a prime number.") else: print(f"{number} is not a prime number.")
Explanation
- Function Definition: The
is_prime
function takes an integernum
as input and returnsTrue
if the number is prime, andFalse
otherwise. - Check for Non-Prime Conditions: The function first checks if the number is less than or equal to 1, which is not a prime number.
- Loop to Check Divisibility: It then iterates from 2 to the square root of the number. If any number in this range divides the input number without a remainder, the input number is not prime.
- Main Program: The program prompts the user to enter a number and then checks if it is prime using the
is_prime
function.
Output
- When you run the above program, it will prompt you to enter a number.
- After entering the number, it will check whether the number is a prime number or not and print the result.
Conclusion
- In this tutorial, we learned how to check if a given number is a prime number using a Python program.
- Understanding this concept is essential for solving various mathematical problems and competitive programming challenges.
- Practice this example to enhance your programming skills and understanding of prime numbers.