Let´s how to do a simple python program where we will check if a number is prime or not
First we define the variable that will have the number that we want to know if it´s a primer number or not
num = 29
Then we definde the variable that will have on it a Boolean(true or false value)
flag = False
Since prime numbers are greater than 1 we will start telling the program that checks if the num variable is greater than 1
if num > 1:
Inside the if statement we put a loop that will check in range from 2 until the value of the num variable that right now is 29
if num > 1:
for i in range(2, num):
Now inside the for loop we will check if the module of num % i is 0 and if it´s it will mean that the number is not prime because it will have more dividers others than 1 and it´s self.
What is break?
break is a word in python that makes a break on the code or to be precise on the loop.
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break
The last part will check if the variable flag is true or false and depending what is it will display if the num variable is a prime number or not.
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
Here is how will look the entire code
num = 29
flag = False
if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
That´s it for now.
Tip:
If you want the num variable to be an user input you can do this instead when defining the variable
num = int(input("Enter a number: "))
Shorter way to do it
num = 11
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print(num, "is not a prime number")
break
elif(num % i) != 0:
print(num, "num is a prime")
break
Top comments (0)