Python Use Loops to Print a Square
We can use Python's loop structures to print a square. Suppose we want to print a square with side length 5; this can be done with nested loops. 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
)
:
(
"*"
,
end
=
" "
)
(
)
Code analysis:
size = 5: Define the side length of the square as 5.for i in range(size):: The outer loop controls the number of rows and runs 5 times.for j in range(size):: The inner loop controls the number of asterisks in each row and runs 5 times.print("*", end=" "): Print one asterisk and add a space after it,end=" "meaning no line break.print(): Print a blank line at the end of each row to achieve a line break.
Output result:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
Python3 Examples