The exercises in this lesson draw shapes in the console using only characters. You do not need anything new from Python: they are the loops and strings you already know. What matters is a way of thinking.
A shape is a list of rows
The console writes line by line, from top to bottom. Drawing a shape therefore means deciding what text goes in each row and showing those rows with a loop:
for row in range(3):
print("*****")
# *****
# *****
# *****
Repeating a symbol with *
You do not need a second loop to write 5 asterisks: string multiplication already does it.
print("*" * 5) # *****
print("ab" * 3) # ababab
print(" " * 4 + "*") # four spaces and an asterisk
So a rectangle of width by height is simply height identical rows of symbol * width. That is the solution of Square and Rectangle.
symbol = input()
width = int(input())
height = int(input())
for _ in range(height):
print(symbol * width)
Two loops: column by column
Another way to draw is with a loop inside another: the outer one goes through the rows and the inner one through the columns. To write every symbol on the same line you use end="", and when the row is finished you do an empty print():
for row in range(3):
for column in range(5):
print("*", end="")
print() # line break at the end of each row
It is longer, but it is essential when the symbol at each position depends on the row and the column (hollow shapes, boards, graphs).
Spaces are drawn too
A space is a character like any other. To shift a row to the right, you put some spaces in front:
for row in range(4):
print(" " * row + "#" * 3)
# ###
# ###
# ###
# ###
That "spaces + symbols" idea is the basis of the parallelogram, the triangles and the pyramid, as you will see in the next article.
Tricks to avoid mistakes
- Test with small sizes (3 or 4) before trying 20.
- The first value of
rangeis 0: the first row hasrow == 0. - If the drawing comes out stuck to the left or with an extra line break, look at where the empty
print()and theendare.