In this python tutorial, you will learn how to write a python program to check if a number is Prime or not.
Prerequisite topics to create this program.
- Python Input, Output
- Python nested if…else statement
- Python Data types
- Python Type Conversion
- Python For loop
- Python break statement
- Python Arithmetic Operator
Note:
1 is not a prime number
prime numbers are the concept of positive integer values.
Steps
- First, we ask the user to enter a number.
- Using the int() function we will convert the entered value into an integer value.
- Using the for loop we will create a loop range from 2 to half of the entered number.
- In the loop we will check if any number can divide the entered integer, if yes then we will break the for loop and print the number is not a prime number
- Throughout the loop, if any number could not divide the entered number then, we will print that the number is a prime.
Python Program to Check Prime Number:
Code:
num = int(input("Enter a Number: ")) if num > 1: for i in range(2,(num//2)+1): if num%i==0: print(num, "is a not prime number") break #this if statement checks if the for loop is completely executed if i==num//2: print(num, "is a prime number") else: print(num,"is not a prime number" )
Output 1:
Enter a Number: 13 13 is a prime number
Output 2: Enter a Number: 16 16 is a not prime number