If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To create a square pattern in Python, you can use nested loops to print rows and columns of stars (or any other character) in a square format. Here's an example of how to create a square pattern using nested loops:
pythonCopy code
def square_pattern(size): for i in range(size): for j in range(size): print("*", end=" ") print() # Example usage: size_of_square = 5 square_pattern(size_of_square)
Output:
markdownCopy code
* * * * * * * * * * * * * * * * * * * * * * * * *
In this example, the
square_pattern()
function takessize
as input, which represents the size of the square (the number of rows and columns). The function uses two nestedfor
loops. The outer loop iterates from 0 tosize - 1
, and the inner loop also iterates from 0 tosize - 1
.During each iteration of the inner loop, a star (*) is printed with the
print("*", end=" ")
statement. Theend=" "
argument ensures that the stars are printed on the same line with a space between them. After each row is printed, theprint()
statement is used to move to the next line to start a new row.When you call the
square_pattern()
function withsize_of_square = 5
, it will create a square pattern with 5 rows and 5 columns, as shown in the output.You can modify the
size_of_square
variable to create square patterns of different sizes. You can also replace the "*" character with any other character or string to create patterns using different symbols.
Comments: 0