Python Printing a Square Using Loops
We can use Python's loop structure to print a square. Suppose we want to print a square with a side length of 5; we can use nested loops to achieve this. The outer loop controls the number of rows, and the inner loop controls the number of asterisks in each row.
Example
size = 5
for i in range(size):
for j in range(size):
print("*", end=" ")
print()
for i in range(size):
for j in range(size):
print("*", end=" ")
print()
Code explanation:
size = 5: Define the side length of the square as 5.for i in range(size):: Outer loop, controls the number of rows, loops 5 times.for j in range(size):: Inner loop, controls the number of asterisks in each row, loops 5 times.print("*", end=" "): Print an asterisk and add a space after it,end=" "Indicates no line break.print(): After each row ends, print a blank line to achieve a line break.
Output result:
* * * * * * * * * * * * * * * * * * * * * * * * *Other Extensions
Python3 Examples