Python Output Square Pattern (Using Asterisks)
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()
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:
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.for i in range(side_length):: This is an outer loop used to control the number of rows in the square.for j in range(side_length):: This is an inner loop used to control the number of asterisks in each row.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.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:
* * * * * * * * * * * * * * * *Other Extensions
Python3 Examples