Geometric shapes · 3 / 13 Theory

Hollow shapes and text graphs

Until now each row was built with a single formula. In hollow shapes, the top and bottom rows are different from the middle ones. You need a condition inside the loop.

Hollow square

The first and last rows are full; the intermediate ones only have the symbol at the edges and spaces in between:

symbol = "#"
width = 5

for row in range(width):
    if row == 0 or row == width - 1:
        print(symbol * width)
    else:
        print(symbol + " " * (width - 2) + symbol)
# #####
# #   #
# #   #
# #   #
# #####

For Draw a hollow square and Draw a hollow rectangle exactly this idea is used. In the rectangle, the last row is height - 1 and the inside is width - 2 spaces wide.

Alternative with two loops

If you paint column by column, you decide the character of each position with a condition on the row and the column:

for row in range(4):
    for column in range(6):
        edge = row == 0 or row == 3 or column == 0 or column == 5
        print("#" if edge else " ", end="")
    print()

Notice that edge is a logical value and that we use the conditional operator (a if condition else b) to choose the character.

Extreme cases

A square of width 1 or 2 has no inside: width - 2 would be 0 or negative. Multiplying a string by a negative number gives the empty string, so the program does not fail, but it is worth testing.

A function graph in the console

A graph is a shape whose size in each row is given by a mathematical formula. If in each row you paint y symbols, the drawing shows how y grows as x changes:

for x in range(0, 6):
    y = x * 2
    print("*" * y)
# (empty row)
# **
# ****
# ******
# ********
# **********

For Graphic of a Function you have to go through the values of x between the start and the end that the statement asks for (remember that the end of range is not included), calculate y with the formula and show a row with that length.

With functions such as (x - 3) ** 2 the graph goes down and up again, forming a curve. When y is 0 the row is empty.

Lesson summary

  • A shape is a list of rows.
  • Each row = spaces + symbols (or a piece of text), with a formula depending on the row.
  • If there are edges, a condition decides which row is special.
  • Before programming, draw by hand and make the table.