In this simple python program, we need to check the given number is prime or not. It's a beginner-level python program.
To understand this example, you should have knowledge of the following Python programming topics:
In this python program, we need to check for a Prime number. A Prime number is a positive number that is divisible by 1 and by that number only. So for a prime number, there will be only two factors.
For example, let us take a number 7, so let's check the 7 is a positive number and divisible by 7 and 1 only, so it is a prime number.
Note: 1 is not a prime number because 1 has only one factor, so we treat it as 1 is not a prime number.
In this simple python program, we need to accept a number from the user and save that into a variable. Now we check the number for prime or not by checking the number is positive or not. If it is not a positive number, we cant check for the prime. We have to use a for loop in python from 2 to the number and check that number is divisible by any number below that number using an if condition in python language. Finally, print the number is prime or not.
STEP 1: Accept the number from the user using the input function in python and store it in a variable.
STEP 2: check the number is greater than 1. If so, move inside the if
condition else
print the number is not prime because it is not a positive number.
STEP 3: Open a for loop
from 2 to the entered number to check for the number's divisibility.
STEP 4: Open an inner if
condition to mod the number with every number from 2 to that number. Print the given number is not a prime number is divisible with any number, and break the loop using the break statement.
STEP 5: If that loop is over and no number is found divisible with the given number, print the given number as a prime number.
num = int(input("Enter any number: ")) # Accept the number from the user.
if num > 1: # check the number is greater than 1.
for i in range(2, num): # for loop to check the number is divisible by any number
if (num % i) == 0: # If condition to check any divisor for the number
print(num, "it is not a prime number")
break # break from the for loop
else:
print(num, "it is a prime number") # if the number is less than or equal to zero then it is not a prime number
else:
print(num, "it is not a prime number")
Enter any number: 7 7 It is a prime number