Python Program to Check Prime Number
Prime numbers are special numbers that have only two factors: 1 and themselves123. This means that they cannot be divided by any other number without leaving a remainder2. For example, 7 is a prime number because it can only be divided by 1 and 7. But 8 is not a prime number because it can also be divided by 2 and 4.
The smallest prime number is 23, which is also the only even prime number3. All other prime numbers are odd
Python Code :
The below Python program checks if a given number is a prime number or not:
# Get input number from user
num = int(input("Enter a number: "))
# Check if the number is prime
if num > 1:
for i in range(2, num):
if num % i == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
In this program, the user is prompted to enter a number. The program then checks whether the number is a prime number using a for loop.
A prime number is a number that is greater than 1 and has no positive divisors other than 1 and itself.
The program then checks whether the number is greater than 1 using the expression num > 1. If it is, the program uses a for loop to iterate through all numbers from 2 to num - 1 using the expression for i in range(2, num).
For each value of i, the program checks whether num is divisible by i using the expression num % i == 0.If it is, the number is not a prime number, and the program breaks out of the loop using the break statement.
Otherwise, the program completes the loop without finding any divisors of num, and therefore num is a prime number. In this case, the program prints out a message saying that num is a prime number using the print statement inside the else block.
If the number is less than or equal to 1, the program prints out a message saying that the number is not a prime number using the print statement outside the for loop.
Note that this program assumes that the user enters a valid integer. If the user enters an invalid input, such as a string or a non-numeric value, the program will raise a ValueError or produce an incorrect result.
For example :
Enter a number: 71
71 is a prime number