DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

Python Prime numbers

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
Enter fullscreen mode Exit fullscreen mode

Then we definde the variable that will have on it a Boolean(true or false value)

flag = False
Enter fullscreen mode Exit fullscreen mode

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:
Enter fullscreen mode Exit fullscreen mode

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):
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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")

Enter fullscreen mode Exit fullscreen mode

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: "))

Enter fullscreen mode Exit fullscreen mode

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  
Enter fullscreen mode Exit fullscreen mode

Top comments (0)