Let’s say we are given a list of numbers and we want to find out whether the numbers are prime numbers. We can check the primality of a number n easily. We can take all numbers from 1 to n and divide n with the number. In other words, we can find out all the factors of the number n. If n has only two factors 1 and n, then n is a prime number.
n = 21 for i in range(2, n): if n % i == 0: print(“The number is a composite number”) else: continue else: print(“The number is a prime number”)
Here, n is a given number. The for loop iterates through 2 to (n – 1). If any number between 2 to (n – 1) divides n, then that number is a factor of n and hence, n is a composite number. If the number does not divide n, then we are using the continue statement to stop the current iteration and continue with the next iteration. If no number from 2 to (n – 1) divides n, then the loop completes execution, and the else statement is executed and the program prints the number is a prime number.
Now, let’s say we are given several numbers and we need to check the primality of each number from different parts of the code. One way to do it is to write repeated loops. But, that will not be very convenient and we need to make a program modular also. So, the best option is to use a Python function.
We can write a block of code within a Python function and then call the function. The block of code will be executed each time the function is called. We can also call a function with different arguments each time. For example, in the above example, we can write a Python function with the above piece of code and call the function each time with a different value of n.
0 Comments