Challenge: Rectangle

Question:

Create a function to print a rectangle with the pattern shown below. The size of the rectangle is the input to the function.

Input: 5
Output:
xxxxx
x   x
x   x 
x   x
xxxxx

Input: 3
Output:
xxx
x x
xxx

Input: 2
Output:
xx
xx

Input: 1
Output: 
x

Answer:

The key here is to separate the printing of the first and last row from the middle rows.

# the function
def rectangle(n):
  for i in range(n):
    if i == 0 or i == n-1:
      print('x'*n)
    else:
      print('x' + ' '*(n-2) + 'x')

# call the function
rectangle(5)

👍 Have fun while coding with Python!

👌 Please Subscribe to receive notifications on future challenges.

💬 If you have any questions simply write a comment down below.

Share