Python By Example

Print Prime numbers up to N

by Jiffin Joachim Gomez on 24th February 2017

This is a simple python program to print prime numbers up to n, where n is the limit. A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

The program asks the user to input the limit which is stored in the variable n, ie., the program prints prime numbers starting from 1 up to n. When reading the user input the int function converts the input to an integer value. This program uses two for loops nested one inside the other. In the outer for loop, the value of num is incremented from 1 to n in each step. In the inner loop we use a variable i whose value is incremented from 2 up to half the value of num

In each iteration of the inner loop, we check the remainder from the division of num by i. If the remainder is zero it means that number num is completely divisible i and therefore num is not a prime number. You can break out of inner loop there an continue checking the next number. If none of the numbers are completely divisible then the loop will finish and goes on to execute the else part which means num is prime.

Program Sources

# Python program to display all the prime numbers upto n

# Setting the intial value with 1
Starting_value = 1

# Taking input from the user
n  = int(input("Enter the number: "))

print("Prime numbers between", Starting_value, "and", n, "are:")
for num in range(Starting_value, n + 1):   
   if num > 1:
       for i in range(2, int(num/2)+1):
           if (num % i) == 0:
               break
       else:
           print(num)

Program Output

Enter the number: 20
Prime numbers between 1 and 20 are: 
2
3
5
7
11
13
17
19

Post a comment

Comments

PRAVEEN G | January 2, 2018 4:30 AM |

Very very nice I love this program

Lily | December 20, 2017 12:34 PM |

I don't understand this bit -> for i in range(2, int(num/2)+1): Why should we divide num by 2 instead of just num + 1?

Remy | December 20, 2017 3:01 PM |

The biggest factor a number can have cannot be more than half of that number. Mathematically we can limit the loop to the square root of the number, which is more accurate and optimized but we are keeping it simpler here.