Drawing Shapes with Python: A Guide to Creating ASCII Art
Drawing shapes using ASCII art in Python can be a fun and creative exercise. In this post, we’ll explore how to create a base class for shapes and extend it to draw different shapes like squares and triangles. We’ll focus on understanding the general properties of shapes and implementing the methods to print them.
The Base Class: Shape
We’ll start with a base class Shape
, which defines some general properties and methods common to all shapes.
class Shape:
def __init__(self, width=5, height=5, print_char='#'):
self.width = width
self.height = height
self.print_char = print_char
def print_shape(self):
for i in range(self.height):
self.print_row(i)
def print_row(self, row_index):
raise NotImplementedError("Subclasses should implement this method.")
In this base class:
__init__
initializes the shape with a default width, height, and character for printing.print_shape
iterates through the height and callsprint_row
for each row.print_row
is a placeholder method that should be implemented by subclasses.
Drawing a Square
Next, let’s create a Square
class that inherits from Shape
and implements the print_row
method.
class Square(Shape):
def print_row(self, i):
print(self.print_char * self.width)
square = Square()
square.print()
Output:
#####
#####
#####
#####
#####
The Triangle Class
Right-Angled Triangle
A right-angled triangle increases the number of characters in each row, forming a simple ascending pattern. This can be achieved by multiplying the print character by the height index plus one.
class Triangle(Shape):
def print_row(self, i):
print(self.print_char * (i + 1))
triangle = Triangle()
triangle.print()
Output:
#
##
###
####
#####
Symmetrical Triangle
To create a symmetrical triangle, we need a width that is double the height. Each row should have an odd number of characters, and the rows should be centered.
class SymmetricalTriangle(Shape):
def __init__(self, height=5, print_char='#'):
super().__init__(width=2*height, height=height, print_char=print_char)
def print_row(self, i):
triangle_width = i * 2 + 1
padding = (self.width - triangle_width) // 2
print(' ' * padding + self.print_char * triangle_width)
sym_triangle = SymmetricalTriangle()
sym_triangle.print()
Output:
#
###
#####
#######
#########
Conclusion
In this blog post, we explored how to use Python classes to create shapes with ASCII art. Starting with a base Shape
class, we extended it to create a Square
, a simple right-angled Triangle
, and a more complex SymmetricalTriangle
. Each shape was printed by iterating over its height and dynamically calculating the number of characters per row.
This exercise demonstrates the power of object-oriented programming and the fun of creating visual representations with code. Whether you’re a beginner or an experienced programmer, drawing shapes with ASCII art is a great way to practice your coding skills and get creative with your projects.