In this example, we will make a program that will check whether a number entered by a user is prime or not. A prime number is one which can only be divided by 1 and itself. For example 7, 13, 19, 23 etc. All these number can only be divided by 1 and themselves.
To understand this example you must have the knowledge of following topics in python –
- Comparison and arithmetic operators
- Conditional statements
num = int(input("Enter a number:")) i = 2 check = 0 while i < num: if num % i == 0: print("The number is not prime") check += 1 break i+=1 if check == 0: print("The number is prime")
Enter a number:13
The number is prime
- First of all we have declared a variable named ‘num’ and storing the integer entered by the user in it.
- Next we have declared a variable named ‘i’ and initialised it by 2. The reason why we have initialized it by 2 is, we need to check whether the number is divisible by a number within the range 2 – the number itself. For example if the number is 11, we need to check whether it is divisible by every number in the range of 2-10. We have not included 1 and the number itself in this range because every number(whether prime or non prime) is divisible by 1 and itself.
- Next we have declared a variable named check and initialized it by 0. I will explain its use in the later steps.
- We are executing a loop that starts from i = 2 until i becomes 1 less than the number given by the user. For example if the user has given 12, the loop will run from 2 – 11. Every time this loop runs we will check whether the user number is divisible by the current value of i. If at any point the condition becomes true, a message saying “The number is not prime” would be displayed, the value of check would be incremented by 1 and the loop would be terminated (as we have written break).
- Once the loop terminates, the only thing we need to check the value of variable ‘check’. If the value inside check is still equal to 0, we can conclude that it has not incremented and so the if condition inside the loop never became true throughout the execution of the loop. If the value of check variable is equal to 0, a message would be displayed that says – “The number is prime”.