☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 3 : Processing : Repetition : Nested Loops

Nested Loops

Subscribe Contact


Contents

Overview

Now that we have learned a bit about while and for loops, now we can consider nested loops. A nested loop structure is constructed by placing one loop inside another loop. This is often called repeating a repetition. Nested loops can be while loops or for loops, or a combination, that is, a for loop nested inside a while loop or visa versa.

General Form

The general form of the code of the nested for loop is as follows:

pre_loop_statement(s)
for outer_loop_variable in sequence:
  for inner_loop_variable in sequence:
    inner_loop_statement_1
    inner_loop_statement_1
    inner_loop_statement_1
    .
    inner_loop_statement_n
  outer_loop_statement_1
  outer_loop_statement_2
  .
  outer_loop_statement_n
post_loop_statement(s)

General Form Details:

  • Nested loops have an outer loop and an inner loop.
  • Notice the indentation in this general form. The inner for loop is indented inside the outer for loop and each of the two loops has its indented statements as well.
  • Each time the outer loop runs (iterates) the inner loop runs the number of times specified in the inner loop signature.
  • See the functional code example below.


Figure 1: General Form of a nested loop

Functional Code Example

The outer loop of the functional code example above iterates five times (0 thru 4) and each time the outer loop runs the inner loop iterates ten times (0 thru 9).



Figure 2: Nested loop example


Figure 3: Output of example nested loop

Code Details:

There are many uses of nested loops. One very common use is working with rows and columns of data, which we will explore when we study data structures a little later in the book.

More Examples

Examples 1 & 2 are intended to be studied and compared.

Example 1

for i in range(5):
  for j in range(5):
      print("*", end="")
  print()

Example 1 Output

*****
*****
*****
*****
*****

Example 2

for i in range(5):
  for j in range(i + 1):
      print("*", end="")
  print()

Example 2 Output

*
**
***
****
*****

Question

Compare the loop signatures between Examples 1 & 2 above and answer the following questions:

  1. Note that in Example 2, we changed the range parameter to i + 1. Why did making this change alter the output to appear as a triangle of * characters, instead of the rectangle of * characters we see in Example 1's output?
  2. What difference would there have been to the output of Example 2 if we had not included + 1 in the Example 2 range parameter?


Examples 3 & 4 add decision statements to demonstrate how to combine decisions with loops to achieve intended results.

Example 3

rows = 5
cols = 5
for i in range(rows):
  for j in range(cols):
    if j < i:
      print(" ", end="  ")
    else:
      print("*", end="  ")
  print()

Example 3 Output

*  *  *  *  *
*  *  *  *
*  *  *
*  *
*

Example 4

rows = 5
cols = 10
for i in range(1, rows + 1):
  for j in range(1, cols + 1):
    if i == 1 or i == rows or j == 1 or j == cols:
        print("*", end=" ")
    else:
        print(" ", end=" ")
  print()

Example 4 Output

* * * * * * * * * *
*                 *
*                 *
*                 *
* * * * * * * * * * 

Question

Questions: Answer the following questions about Examples 3 ad 4:

  1. Example 3: What is the purpose of the if j < i if statement in the Example 3 code?
  2. Example 3: What would be the effect of changing Line 5 to if i < j? And why?
  3. Example 4: What is the purpose of the compound if decision on Line 5?
  4. Example 4: How could you change this code to print the box with double the spaces between the * characters and also a blank line between each row in the rectangle shape? Like this (compare this to the Example 4 Output above):
*   *   *   *   *   *   *   *   *   *

*                                   *

*                                   *

*                                   *

*   *   *   *   *   *   *   *   *   *


Tracing Nested Loop Execution

When you are learning programming structures, especially those that repeat steps, it is often very useful to manually trace the execution of that structure. For loops, this is called loop tracing. When we trace code execution it is important to, first, understand how the structure works and, second, to write out each step the way the interpreter will execute each step in the computer.

For example, consider the following nested for loop:

for i in range(4):
print("Row", i + 1, sep=" ", end=": ")
for j in range(3):
    print(j + 1, end=" ")
print()

Output:

Row 1: 1 2 3
Row 2: 1 2 3
Row 3: 1 2 3
Row 4: 1 2 3 

Execution Trace Table

i Iteration print("Row", i+1) j iterations print()
0 Row 1:
j Iteration print(j + 1)
0 1
1 2
2 3
1 Row 2:
j Iteration print(j + 1)
0 1
1 2
2 3
2 Row 3:
j Iteration print(j + 1)
0 1
1 2
2 3
3 Row 4:
j Iteration print(j + 1)
0 1
1 2
2 3


Practice Problems

Problem 1

Write a Python program that prints a triangle of digits using nested for loops. Prompt the user several rows, then for that number of rows print the row number repeated each row's number of times. Here is an example of the prompt and output:


Please enter the number of rows: 5
1
22
333
4444
55555



Problem 2

Write a Python program that prompts the user for an integer value and then uses nested for loops to create a multiplication (times) table based on that number. For example, if the user enters 5, your program should produce the times table displayed below. Notice the spacing between numbers on each row and the blank lines between rows, your program should produce that spacing as well. Hint: Take a look at the Escape Sequences page for help with the spacing of the rows and columns in your output.

1  2  3  4  5

2  4  6  8 10

3  6  9 12 15

4  8 12 16 20

5 10 15 20 25 




 





© 2023 John Gordon
Cascade Street Publishing, LLC