In this post, I am going to write a simple Python 3 program to print the Prime numbers within a limit. Firstly, Let me explain what is a prime number.
If you don’t know what is a prime number, here is a small explanation:
- 1 is divisible by itself only (divisible by 1 natural number, so not a prime number)
- 2 is divisible by itself and also can be divisible by 1 (divisible by 2 natural numbers, so it a prime)
- 3 is also divisible by itself and by 1 (divisible by 2 natural numbers, so it a prime)
- But, 4 is divisible by itself as well as by 2 and by 1 (divisible by 3 natural numbers, so it is not a prime number)
- 5 is divisible by itself and by 1 (divisible by 2 natural numbers, so it is a prime number)
- 6 is divisible by itself and by 3 and by 2 and by 1 (so it is divisible by 4 natural numbers, so it is not a prime number)
Here is the Python function to print Prime numbers within a limit:
1 2 3 4 5 6 7 8 9 |
def print_prime(limit): for i in range(1, limit + 1): c = 0 for j in range(1, i + 1): if (i % j == 0): c = c + 1 if c == 2: print (i) |
So basically you just have to call the print_prime() function pass the limit as an argument to the function to print the Prime numbers.
Here is the usage of the above function for you:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def print_prime(limit): for i in range(1, limit + 1): c = 0 for j in range(1, i + 1): if (i % j == 0): c = c + 1 if c == 2: print (i) print ("Print Prime numbers in Python 3:") print ("Enter the limit:") limit = int(input()) print ("Prime numbers are:") print_prime(limit) |
This above example snippet will ask you to first enter the limit, once it is entered then it will print the prime numbers for you.
This is the sample output of the above snippet:
1 2 3 4 5 6 7 8 9 10 11 12 |
Print Prime numbers in Python 3: Enter the limit: 20 Prime numbers are: 2 3 5 7 11 13 17 19 |
I hope this post would have helped you to understand how to print Prime number using Python. Thanks for your time and welcome! 🙂
You can also check my previous post “Python program to find a number is a prime number or not!“.