We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2
def print_square_pattern(n):
for i in range(n): for j in range(n): print("*", end=" ") # Print '*' character with space between print() # Move to the next line after each row
# Call the function with a square size of 5
n = 5 print_square_pattern(n) Output: markdown Copy code * * * * * * * * * * * * * * * * * * * * * * * * * Explanation: The function print_square_pattern(n) prints a square pattern of size n x n, filled with asterisks (*). The outer for loop runs for n rows. The inner for loop prints n stars (*) in each row. The print() statement with no arguments moves to the next line after printing each row. Example 2: Square Pattern with Numbers (1, 2, 3...) python Copy code def print_number_square(n): num = 1 # Start with number 1 for i in range(n): for j in range(n): print(num, end=" ") # Print the current number num += 1 # Increment the number for the next print print() # Move to the next line after each row
# Call the function with a square size of 4
n = 4 print_number_square(n) Output: Copy code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Explanation: This pattern prints a square of numbers in a sequence from 1 up to n*n. The num variable starts at 1, and it is incremented after each number is printed. Example 3: Hollow Square Pattern (Border of Asterisks) python Copy code def print_hollow_square(n): for i in range(n): for j in range(n): # Print '*' only on the borders of the square if i == 0 or i == n - 1 or j == 0 or j == n - 1: print("*", end=" ") else: print(" ", end=" ") # Fill inside with spaces print() # Move to the next line after each row # Call the function with a square size of 5 n = 5 print_hollow_square(n) Output: Copy code