Square Patterns in Python

In the previous article we explored Nested Loops, now starting from this article we will look at a series of pattern related programs. First we will start with the square type pattern. Suppose the user enters a number n, the program should return a star pattern with the size n*n. Example for the input of value 4 it would return

* * * *
* * * *
* * * *
* * * *

If the input was 2 it would look like:

* *
* *

However, if the value is only 1. Then it would look like:

*

Implementation of Square Patterns in Python

We will use the range( ) function to return the range 0 to n-1 of numbers for the square pattern. We would also need to print the range again multiple times according to the respective number so we would use a loop to iterate through the process as many times as needed to obtain the right result.

n=int(input("Enter n:"))
for in in range(n):
    for j in range(n)
        print("*", end=" ")
    print()
Output:
Enter n:8

* * * * * * * * 
* * * * * * * * 
* * * * * * * * 
* * * * * * * * 
* * * * * * * * 
* * * * * * * * 
* * * * * * * * 
* * * * * * * * 

The program iterates through the looping structure and prints the * star character symbol as many times within a single line as the number entered as well as repeats the line as many times as the number. It nests the loop for the number of lines within the loop structure for the number of characters.

Hence, we have seen the code and implementation of the Square Patterns in Python, in the next article we will explore printing the triangle pattern.

Leave a Comment