Exercise
Function To Display A Rectangle
Objective
Develop a Python program that defines a function to print a filled rectangle on the screen, where the dimensions (width and height) are provided as parameters. For example, calling the function WriteRectangle(4, 3) will output:
****
****
****
Additionally, create a function WriteHollowRectangle that prints only the border of the rectangle. For example, WriteHollowRectangle(3, 4) will output:
****
* *
* *
****
Example Python Exercise
Show Python Code
# Function to print a filled rectangle
def WriteRectangle(width, height):
# Loop through the rows
for i in range(height):
# Print a row of '*' characters with the given width
print('*' * width)
# Function to print a hollow rectangle
def WriteHollowRectangle(width, height):
# Print the top border
print('*' * width)
# Print the middle rows with hollow spaces
for i in range(height - 2):
print('*' + ' ' * (width - 2) + '*')
# Print the bottom border if height is greater than 1
if height > 1:
print('*' * width)
# Example usage
print("Filled Rectangle (4x3):")
WriteRectangle(4, 3) # Print filled rectangle of width 4 and height 3
print("\nHollow Rectangle (3x4):")
WriteHollowRectangle(3, 4) # Print hollow rectangle of width 3 and height 4
Output
python rectangle.py
Filled Rectangle (4x3):
****
****
****
Hollow Rectangle (3x4):
****
* *
* *
****
Share this Python Exercise