In this tutorial, we are going to learn a python program to print all the prime numbers that are smaller than or equal to the number given as an input by the user.

## Problem Statement

For any number that is input by the user, we have to print all the prime numbers.

**For example:**

**Case1:** If the user inputs number 12

then the output should be ‘2, 3, 5, 7, 11’.

**Case2:** If the user inputs a number 51.

then the output should be ‘2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 ’

## What are prime numbers?

**Prime Numbers** are the numbers that have only 2 factors 1 and the number itself. It is only defined for the number which is greater than ‘1’.

‘2’ is the smallest prime number.

**Some examples:**

- 5 is a prime number because only factors of 5 are ‘1 and 5’.
- 11 is a prime number because only factors of 11 are ‘1 and 11’.
- 10 is not prime because the factors of 10 are ‘ 1,2,5 and 10’.

## What are composite numbers?

The number which is greater than ‘1’ and is not a prime number is called a **composite number.**

**Some examples:**

- 4 is a composite number because it is not prime and has factors 1, 2, and 4’.
- 10 is a composite number because it is not prime and has factors 1, 2, 5, and 10’.
- 21 is a composite number because it is not prime and has factors 1, 3, 7, and 21’.

Now let’s have a look at **‘nested for loop’** which we are going to use in our program.

## Our Logic to print first n prime numbers

- Our program will take integer input from the user. This integer is the number limit till where we need to find all prime numbers.
- We need to iterate through every number below that input integer and check if it is a prime number or not simultaneously.
- If the iterated number is found prime number then print that number as an output.

## Algorithm to print first n prime numbers

Step 1: Start

Step 2: take input from the user.

Step 3: for n in range(1,num):

for i in range(2,n):

if(n%i==0):

break

else:

print ‘n’

Step 4: Stop

## Python Program to print first n prime numbers

**Output 1:**

**Explanation:**

The input number is 10, so our program will check all the numbers smaller than 10 and greater than 0. The numbers that do not have any other factor other than 1 and itself, i.e. prime numbers which are smaller than 10 are 1,2,3,5, and 7.

**Output 2:**

**Explanation:**

The input number is 12, so our program will check all the numbers smaller than 12 and greater than 0. The numbers that do not have any other factor other than 1 and itself, i.e. prime numbers which are smaller than 10 are 1,2,3,5, 7, 9, and 11.