DEV Community

Muthu
Muthu

Posted on

1 3

Print * as a box

maxRows = 10
maxCols = 100
for i in range(maxRows):
    star = "*"
    for j in range(maxCols-2):
        if(i==0 or i==maxRows-1):
            star = star + "*"
        else:
            star = star + " "
    print(star+"*")
Enter fullscreen mode Exit fullscreen mode

printStar

Top comments (3)

Collapse
 
protium profile image
protium

What about

n, m
print("*" * n)
print(("*" + " " * (n-2) + "*\n") * m - 2)
print("*" * n)

(sorry, I can't sleep)

Collapse
 
mu profile image
Muthu • Edited

it throws error... but fixed it and the latest is

n=10
m=5
print("*" * n)
print(("*" + " " * (n-2) + "*\n") * (m - 2))
print("*" * n)

error

But how to avoid the unnecessary new line, @protium ?

Collapse
 
protium profile image
protium • Edited

Sorry, I didn't test it. You could add another print before the last line and multiply by m - 3. But notice that the code I wrote is awful and has a terrible performance. I just wanted to point out what awesome things you can do with python.

A good practice will be to solve it with just one for loop. It will have the same time complexity but it implies more math.

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay