How to generate a square pattern in Python
Several patterns can be printed using Python, once we have a strong grip over the concepts involving loops. Here, we will be using simple for loops to generate a square pattern using numbers.
Description
A square is a plane figure consisting of four sides that are identical in terms of magnitude. It has four angles, all of which are 90 degrees.
To execute this figure using Python programming, we will be using two methods.
One with two for loops:
- An outer loop: To loop through the number of rows.
- An inner loop: To print the patterns along the columns.
Code
Let’s look at the below code snippet.
# No of rowsn = 4# Loop through rowsfor i in range(n):# Loop to print patternfor j in range(n):print('*' , end=' ')print()
Explanation
-
In line 2, we take the input for the number of rows (i.e., length of the square).
-
In line 5, we create a
forloop to iterate through the number of rows. -
From lines 8 and 9, an inner nested loop runs, printing
*along the rows and columns, thereby generating the given pattern. Theendstatement helps to stay on the same line. -
In line 10, the
print()statement is used to move to the next line.
Second method is by using list comprehension and join() method:
Code
Enter the size and then click the "Run" button to execute the code.
size = int(input())print("")pattern = [["*" for _ in range(size)] for _ in range(size)]for row in pattern:print(" ".join(row))
Enter the input below
Explanation
Line 1: Takes the size of the square pattern from the user and stores the input as an integer in the variable
size.Line 3: This line creates a square pattern by using list comprehension.
Line 4: The loop is initiated that iterates over each row in the
patternlist.Line 5: This prints each row of the pattern with space-separated characters.
Learn the basics with our engaging Learn Python course!
Start your coding journey with Learn Python, the perfect course for absolute beginners! Whether you’re exploring coding as a hobby or building a foundation for a tech career, this course is your gateway to mastering Python—the most beginner-friendly and in-demand programming language.With simple explanations, interactive exercises, and real-world examples, you’ll confidently write your first programs and understand Python essentials. Our step-by-step approach ensures you grasp core concepts while having fun along the way. Join now and start your Python journey today—no prior experience required!