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

Python Print a Square Pattern (Using Asterisks)

Python Print a Square Pattern (Using Asterisks)

Document Object Reference Manual Python3 Examples

In this example we will write a simple Python program that prints a square pattern made of asterisks (*). The user enters the side length of the square, and the program prints the square accordingly.

Example

Get the square side length entered by the user

side_length

=

int

(

input

(

"Please enter the side length of the square: "

)

)

Use nested loops to print the square

for

i

in

range

(

side_length

)

:

   

for

j

in

range

(

side_length

)

:

       

print

(

"*"

,

end

=

" "

)

   

print

(

)

Code analysis:

  1. side_length = int(input("请输入正方形的边长: ")): This line gets the square side length entered by the user and converts it to an integer.
  2. for i in range(side_length):: This is an outer loop that controls the number of rows of the square.
  3. for j in range(side_length):: This is an inner loop that controls the number of asterisks in each row.
  4. print("*", end=" "): This line prints one asterisk and adds a space after it,end=" " meaning that printing does not move to a new line.
  5. print(): This line breaks the line at the end of each row so that the next row can start printing.

Output: assuming the user enters a side length of 4, the program prints the following square pattern:

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

Document Object Reference Manual Python3 Examples