Welcome folks today in this post we will be checking if a number is prime
or not in python. All the source code of the application is given as below.
Get Started
In order to get started just make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# Program to check if a number is prime or not num = 407 # To take input from the user #num = int(input("Enter a number: ")) # prime numbers are greater than 1 if num > 1: # check for factors for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") # if input number is less than # or equal to 1, it is not prime else: print(num,"is not a prime number") |
So now just run the below script to execute it
python app.py
As you can see 407
number is not prime as prime numbers are those numbers which are only divisible
by 1 or by itself.
You can also take the number as the input
from the user as shown below in the script
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# Program to check if a number is prime or not # To take input from the user num= int(input("Enter a number: ")) # prime numbers are greater than 1 if num > 1: # check for factors for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") # if input number is less than # or equal to 1, it is not prime else: print(num,"is not a prime number") |
This time we have taken the number from the user as command line
input and you can see 23
is a prime number