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
* * * * * * * * * * * * * * * * * * * * * * * * *
How it works
- The outer loop runs once for each row, and the inner loop prints one star for each column of that row.
- Both loops run
sizetimes, so the square has 5 rows of 5 stars, 25 stars in all. 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.- The empty
print()after the inner loop starts the next row.
Other ways to write it
Using string repetition
* * * * * * * * * * * * * * * * * * * * * * * * *
"* " * size builds a whole row in one go, so the inner loop is not needed.
Rectangle of numbers
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises