How to Draw a Square in Python (Step-by-Step Guide)
"The magic of programming lies in transforming lines of text into something visible and concrete, and every small step opens the door to infinite possibilities."
n = 5
for i in range(n):
print("* " * n)
In this guide, you’ll learn how to draw a square in Python in different ways: from a simple square with asterisks in the console, to graphical squares using libraries like Turtle, Pygame, and Matplotlib.
This is a perfect exercise for Python beginners, as it allows you to practice loops, functions, and graphics libraries step by step.
Drawing a Square with Asterisks in Python (Basic)
The simplest way to print a square in Python is by using print()
and for
loops:
# Square with asterisks in Python
n = 5 # square size
for i in range(n):
print("* " * n)
Output for n = 5
:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
This technique is ideal if you are just starting out and want to practice control structures in Python.
Drawing a Square in Python with Turtle
The Turtle library is one of the most popular ways to get started with graphics programming in Python.
import turtle
t = turtle.Turtle()
for i in range(4):
t.forward(100) # move forward
t.right(90) # turn 90 degrees
turtle.done()
This opens a graphics window and draws a square with 100-pixel sides.
Drawing a Square in Python with Pygame
If you want to create interactive windows and games in Python, the Pygame library is the best choice.
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 400))
pygame.display.set_caption("Square in Python")
# Colors (R, G, B)
white = (255, 255, 255)
red = (255, 0, 0)
running = True
while running:
screen.fill(white)
pygame.draw.rect(screen, red, (100, 100, 200, 200))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
This code creates a Python window with a red square.
Drawing a Square in Python with Matplotlib
With Matplotlib you can plot figures using coordinates. It is widely used in data science and graphical visualization with Python.
import matplotlib.pyplot as plt
x = [0, 1, 1, 0, 0]
y = [0, 0, 1, 1, 0]
plt.plot(x, y, 'b-')
plt.title("Square in Python")
plt.show()
This displays a chart with a blue square.