Search code examples
pythonrectangles

Hollow Rectangle with Asterisks


I know there are numerous way to do this but I am trying to print a rectangle using ranges and if else statements. My code is below works but only cause I have hard coded the spaces required in print statement at line 7. As soon as the values for num_rows or num_cols changes the spacing is off. What do I need to do to make it work?

num_rows = 5
num_cols = 6

for i in range(num_rows):
    print('*', end=' ')
    if i in range(1,num_rows -1):
        print('       ','*', end='')
else:
    for j in range(num_cols-1):
        print('*', end=' ')
print('')

I got the code to turn into the code below after tinkering but it still is not the right and doesn't work once I change the values for the row and cols variables. I am not sure what I need to do to my size variable to be flexible and work with any values for num_rows and num_cols. Is it possible to make this work using only what I have covered so far in my class which is basically whats above lol. I have asked my teacher for help and he stated that I should try searching forums for help first. He stated that most developers do that everyday so I need to get used to asking help.

num_rows = 5
num_cols = 6
size =(num_rows  + 3)

for i in range(num_rows):
    print('*', end=' ')
    if i in range(1,num_rows -1):
        print( ' ' * size + '*', end='')
else:
    for j in range(num_cols-1):
        print('*', end=' ')
print('')

Solution

  • Python makes it easier to do more with less code.

    You could make the rectangle like

    print("* "*num_cols, end='')
    print(("\n* "+"  "*(num_cols-2)+"* ")*(num_rows-2))
    print("* "*num_cols)
    

    Line 1 prints num_cols *s without a newline after that.
    Line 2 prints num_rows-2 lines where each line consists of a * at each end with num_cols-2 number of (spaces) in between.
    Line 3 prints the bottom of the rectangle.

    Your program should work fine if the number of spaces printed is changed from

    print( ' ' * size + '*', end='')
    

    to

    print( '  ' * (num_cols-2)+ '*', end='')
    

    Two spaces are needed because you have end=' ' in print()s before it. If their end is made end='', one space would suffice.