Nested Loops in Python
Problem: Finding Ordered Pairs
Consider the following problem:
Find the number of ordered pairs of positive integers whose product is 100. Note that order matters: (2, 50) and (50, 2) are two different pairs.
Solution
The code above is an example of a nested loop. Lines 2-5 form the outer loop while lines 3-5 form the inner loop. There are multiple levels of indentation here:
- Line 3 begins a new
forloop. - Line 4 is indented with respect to line 3.
- Line 5 is indented with respect to line 4.
This problem could have been solved without using a nested loop. The nested loop is not an efficient solution. It is left as an exercise to the reader to come up with a more efficient solution to this problem.
Problem: Counting Prime Numbers
Find the number of prime numbers less than n, where n is some positive integer.
Solution
Explanation
The basic idea behind the solution is as follows:
- The outer
forloop goes through each element in the sequence 2, 3, ..., n.iis the loop variable for this sequence. - We begin with the guess that
iis prime. In code, we do this by settingflagto beTrue. - Now, we go through all potential divisors of
i. This is represented by the sequence 2, 3, ...,i - 1. Variablejis the loop variable for this sequence. Notice how the sequence for the inner loop is dependent oni. - If
jdividesi, thenicannot be prime. We correct our initial assumption by updatingflagtoFalsewhenever this happens. Ifjdoesn't divideifor anyj, theniis prime, andflagstaysTrue. - Once we are outside the inner loop, we check if
flagisTrue. If that is the case, then we incrementcount, as we have hit upon a prime number.
Important Points About Nested Loops
- Nesting is not restricted to
forloops. Any of the following combinations are possible: forinsideforforinsidewhilewhileinsidewhilewhileinsidefor- Multiple levels of nesting are possible.
While vs. For Loops
for loops are typically used in situations where the number of iterations can be quantified, while while loops are used when the number of iterations cannot be quantified exactly.
Example: For Loop
In this code, the number of iterations varies each time the code is run with a different input. However, given the knowledge of the input, the number of iterations is fixed.
Example: While Loop
In this case, the number of iterations can only be determined after it terminates. There is no way to quantify the number of iterations as an explicit function of user input.
Print Function: end and sep
Problem: Printing Numbers from 1 to n
Accept a positive integer n as input and print all the numbers from 1 to n in a single line separated by commas.
For a given value of n, say n = 9, we want the output to be:
Solution
For n = 9, this will give the required output:
The print function's default behavior is to append a newline after each output. By using the end argument, we can change this behavior.
Example of end
Output:
Separator with sep
If multiple expressions are passed to the print function, it prints all of them in the same line, adding a space between adjacent expressions.
Example:
Output:
If we do not want the space or want a different separator, we can use sep:
Output:
We could also have an empty string as the separator:
Output:
Using end and sep Together
Problem: Print Pattern
Accept a positive integer n, which is also a multiple of 3, as input and print the following pattern:
For n = 9, we would like to print:
Solution
Notice that the for loop iterates in steps of 3 starting from 1. To print the comma-separated triplet i,i + 1,i + 2, sep is set to ,. After printing each triplet, the symbol | is printed by setting end to |. The last print statement ensures the prompt moves to the next line once the pattern is printed. You can try removing the last line and see how that changes the output.