CMU 15-110: Principles of Computing
Nested Loops
Nested for loops
- printRectangle
def printRectangle(n): for row in range(n): for col in range(n): print(str(row) + ',' + str(col), end=' ') print() print(printRectangle(5))
- starRectangle
def starRectangle(n): result = '' for row in range(n): for col in range(n): result += '*' result += '\n' # add a newline to the string! return result print(starRectangle(5))
- printTriangle
def printTriangle(n): for row in range(n): for col in range(row+1): print(str(row) + ',' + str(col), end=' ') print() print(printTriangle(5))
- starTriangle
def starTriangle(n): result = '' for row in range(n): for col in range(row+1): result += '*' result += '\n' # add a newline to the string! return result print(starTriangle(5))