Python Print a Square Pattern (Using Asterisks)
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
)
:
(
"*"
,
end
=
" "
)
(
)
Code analysis:
side_length = int(input("请输入正方形的边长: ")): This line gets the square side length entered by the user and converts it to an integer.for i in range(side_length):: This is an outer loop that controls the number of rows of the square.for j in range(side_length):: This is an inner loop that controls the number of asterisks in each row.print("*", end=" "): This line prints one asterisk and adds a space after it,end=" "meaning that printing does not move to a new line.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:
* * * *
* * * *
* * * *
* * * *
Python3 Examples