Editor

Python Program to Print a Square Star Pattern

Beginner · Patterns

A square star pattern prints the same number of stars on every row, with as many rows as there are stars in a row, so the result is a filled square. It is the simplest nested-loop pattern and a good first step before triangles and pyramids.

Program

square_pattern.py
size = 5 # or: size = int(input("Enter the size of the square: "))
for row in range(size):
for col in range(size):
print("*", end=" ") # a star, then a space
print() # move to the next line
Output
* * * * * 
* * * * * 
* * * * * 
* * * * * 
* * * * *

How it works

  1. The outer loop runs once for each row, and the inner loop prints one star for each column of that row.
  2. Both loops run size times, so the square has 5 rows of 5 stars, 25 stars in all.
  3. end=" " puts a space after each star instead of a new line, and because characters are taller than they are wide, the spaces make the square look square.
  4. The empty print() after the inner loop starts the next row.

Other ways to write it

Using string repetition

Using string repetition
size = 5
for row in range(size):
print("* " * size)
Output
* * * * * 
* * * * * 
* * * * * 
* * * * * 
* * * * *

"* " * size builds a whole row in one go, so the inner loop is not needed.

Rectangle of numbers

Rectangle of numbers
rows = 4
cols = 6
for row in range(1, rows + 1):
for col in range(1, cols + 1):
print(col, end=" ")
print()
Output
1 2 3 4 5 6 
1 2 3 4 5 6 
1 2 3 4 5 6 
1 2 3 4 5 6

Separate rows and cols turn the square into a rectangle, and printing the column number instead of a star numbers each column.

Try it yourself

Change the program so it prints a rectangle of # characters, 4 rows high and 7 wide.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises