Home > Mobile >  Hollow-box star pattern in python
Hollow-box star pattern in python

Time:07-30

In this problem, what is the role of print() at the last? and why its affecting the code output if not included?

n = int(input("Enter the number: "))
for i in range(n):
    for j in range(n):
        if(i==0 or i==n-1 or j==0 or j==n-1):
            print("*", end=' ')
        else:
            print(" ", end=' ')
    print()

Output: For a number (Say '3')

without print() -

* * * *   * * * *

with print() -

* * * 
*   * 
* * *

CodePudding user response:

When you are printing asterisks or spaces with:

print("*", end=' ')

and

print("", end=' ')

those print statements are not advancing a line due to the "end=' '" bit. That is why you get either an asterisk or space printing one after another. The line of code:

print()

isn't actually printing anything, but it is sending a carriage return and line feed to advance to the next line. So if you have a print statement that does not include the "end=' '" directive, your terminal output will advance to the next line.

  • Related