Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Use Loops to Print a Square

Python Use Loops to Print a Square

Document Object Reference Manual Python3 Examples

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

)

:

       

print

(

"*"

,

end

=

" "

)

   

print

(

)

Code analysis:

Output result:

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

Document Object Reference Manual Python3 Examples