Nested loop in python
Nested Loops
Suppose we wish to develop a function to print multiplication tables, one for each of the first (say 10), natural number. Further, in the table, maltiples of a number are to be arrange vertically in a column.
in order dthat the output of the program appears nicely, we would like that each number be printed using at least the number of positions specified in the format string. This may be done as follow (5 digits are reserved for each number which is left padded with spaces):
>>> for i in range(1,4):
print('{0: >5} '.format(i*9))
9
18
27
Also, we would like that the output of several calls to print function may be printed on the same line. For this purpose, we need to use empty string('') in place of the default newline. This can be achieved using keyword argument end. For example,
>>> for i in range(1,4)
print('{0: >5} ' .format(i*9), end ='')
9 18 27
indeed, the code segment
>>> for i in range(1,4):
print('{0: >5} ' .format(i*9))
is equivalent to:
>>> for i in range(1,4) :
print('{0: >5} '.format(i*9), end ='\n')
To develop such a function, we would require two parameters: the number of tables, (say, nTables) to be printed, and the number of multiples (say, nMultiples) of each number to be printed. The skeletion of a function for this purpose is given.
To print the multiplication table, we need to print nMultiples (=10) raws, one for each multiplication of the number num. Skeletion of the code segment for printing multiplication table is given below:
for multiple in range(1, nMultiples +1):
# print a row of multiples of each number num
Next, to print one row of a multiples of all number i.e, multiples of num in the range(1, nTables+1), we may iterate over num using a for loop as follows:
for num in range(1, nTables +1):
print('{0: >2} '.format(num),'*', \
'{0: >2}' .format(multiple), '=', \
'{0: >3}'.formate(num*multiple),'\t',end = '')
print()
Note the use of the keyword argument end in the print function under the for loop, as we want the output of the entire loop to appear on the same line. Finally, when the for loop completes, invoking the print function moves the control to the next line for printing the next row of the multiplication table. The character backslash(\) used at the end of second and third line is a line continuation character that can be used for wrapping long line i.e, of we wish to extend a statement over multiple lines.
0 Response to "Nested loop in python"
Post a Comment