Prime Number in Python

Python Program: A Number is prime or not

In this blog, Let us see how we can write a python code to check if a number is a prime.



Code:

num = int(input("Enter a Number:"))
if num == 1:
    print("1 is not a prime number")

else:
    for i in range(2,num):
        if num%i == 0 :
            print(f"{num} is not a prime number")
            break

    else:
        print(f"{num} is a prime number")
        

Output:

Enter a Number:67 67 is a prime number

Explanation:

  • First, we are getting the input from the user using the input() function.
  • Second, we are converting it into an int data type using the int() function and storing it in a num variable. 
  • Third, we check if the number is equal to 1, if it is true then it will print "1 is not a prime number", because one is not a prime number. If it is false it will run else block. 
  • Fourth, In else, we have a for loop we have a control variable with a range of 2 to num-1, inside the for loop we have an if condition, where it checks if num%i i.e remainder of i is equal to zero or not if it is true it will print "num is not a prime number" and if it is false it will exit the loop and run else block where it will print "num is a prime number". 
  •  Note: num%i == 0 should be false for all the values of i for num to be a prime number.

teamcoderadmin

Post a Comment

Previous Post Next Post