Stars Problem

Write a function that when called, prints the first n rows of a lower triangle filled with asterisks. For example, if the function is called with 5, the following output would be produced:

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

Solution:

# stars.py

def stars(num_stars):
    line = ""
    for i in range(num_stars):
        line = line + "*"
        print(line)

stars(5)

The Table Problem

Now let’s take another look at nested for-loops. Here’s our problem:

Write a program that prints an n (the number of rows from 1 to n) by m (the number of columns from 1 to m) multiplication table. For example, table(4,5) might produce:

  * |  1  2  3  4  5
  --+---------------
  1 |  1  2  3  4  5
  2 |  2  4  6  8 10
  3 |  3  6  9 12 15
  4 |  4  8 12 16 20

Let’s approach this problem by focusing first on the central portion of the table, the rows of products.

# tables.py
 
def table(rows, columns):
    header = "*  |" 
    for column in range(1, columns + 1):
            header = header + str(column).rjust(5)
    print(header)

    border = "---+" + ("-----" * columns)
    print(border)
    for row in range(1, rows + 1):
        line = ""
        line = str(row).ljust(3) + "|"
        for column in range(1, columns + 1):
            line = line + str(row * column).rjust(5)
        print(line)

table(10, 1)