Python program to print first n prime numbers

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:

  1. 5 is a prime number because only factors of 5 are โ€˜1 and 5โ€™.
  2. 11 is a prime number because only factors of 11 are โ€˜1 and 11โ€™.
  3. 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:

  1. 4 is a composite number because it is not prime and has factors 1, 2, and 4โ€™.
  2. 10 is a composite number because it is not prime and has factors 1, 2, 5, and 10โ€™.
  3. 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.

Python Program to print first n prime numbers

#taking input from the user
num = int(input("Enter a number to check even/odd: "))  
#if number is divisible by 2
if num%2 == 0:
   print(num,"is even number")
else:
   print(num,"is odd number")

Output:

Enter a number to check even/odd: 10
10 is even number

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.

What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now