Drawing a Square with Asterisks in Python (Step-by-Step Guide)
"Every figure you build with code is a small brick in the building of your learning."
def draw_square(n, filled=True):
for i in range(n):
if filled or i == 0 or i == n-1:
print("*" * n)
else:
print("*" + " " * (n-2) + "*")
In this tutorial, you will learn step by step how to draw a square with asterisks in Python. We’ll start with simple examples for beginners and then move on to more advanced techniques to create custom squares and align them.
Basic concepts in Python for drawing with asterisks
In Python, we use the print() function to display text in the console.
The asterisks "*"
have no special meaning, they are simply characters that we can repeat.
Basic example:
print("**")
print("*")
print("***")
Output:
**
*
***
With this, we can start forming patterns.
How to draw a basic square with asterisks in Python
A square is simply a block of asterisks with the same number of rows and columns.
Example with for
and string repetition
# Draw a 5x5 square
for i in range(5):
print("*" * 5)
Output:
*****
*****
*****
*****
*****
Here the *
operator allows us to repeat a character in Python.
Drawing a square with borders in Python
Instead of a solid block, we can create only the outline of the square.
n = 5
for i in range(n):
if i == 0 or i == n-1: # first and last row
print("*" * n)
else: # middle rows
print("*" + " " * (n-2) + "*")
Output:
*****
* *
* *
* *
*****
Here we combine loops in Python with if conditionals.
Dynamic square: controlling size with variables
We can ask the user to choose the size of the square:
n = int(input("Square size: "))
for i in range(n):
print("*" * n)
This way, the square is flexible and adapts to the input.
Advanced: Python function to draw squares
We can define a function in Python to reuse the code and decide whether we want a solid or hollow square:
def draw_square(n, filled=True):
for i in range(n):
if filled or i == 0 or i == n-1:
print("*" * n)
else:
print("*" + " " * (n-2) + "*")
# Examples:
draw_square(4, True) # solid square
draw_square(6, False) # hollow square
Expert level: aligned and styled square in the console
We can also center the square so it looks more organized:
n = 5
for i in range(n):
print(("*" * n).center(20))
Output (centered in a width of 20 characters):
*****
*****
*****
*****
*****