Python Output Square Pattern (Using Asterisks)

Document 对象参考手册Python3 Examples

In this example, we will use Python to write a simple program to output a square pattern made of asterisks (*). The user will input the side length of the square, and the program will print the corresponding square based on the entered side length.

Example

# Get the side length of the square 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 Explanation:

  1. side_length = int(input("请输入正方形的边长: ")): This line of code is used to get the side length of the square entered by the user and convert it to an integer type.
  2. for i in range(side_length):: This is an outer loop used to control the number of rows in the square.
  3. for j in range(side_length):: This is an inner loop used to control the number of asterisks in each row.
  4. print("*", end=" "): This line of code is used to print an asterisk and add a space after it,end=" "indicating that no newline is printed after printing.
  5. print(): This line of code is used to add a newline at the end of each row, so as to start printing the next row.

Output Result: Assuming the user enters a side length of 4, the program will output the following square pattern:

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

Document 对象参考手册Python3 Examples

Other Extensions