Marjorie Halili
Marjorie Halili

Reputation: 1

Nested loops print star(*) [python]

Output is:

The code below is equal to the expected output. I just want to ask why is it needed to print() first when printing a single asterisk, but it is not needed when printing more than one asterisk.

n = '*'

for i in range(1,7):    
    for j in range(1,6):

        if i == 1 and j < 6:
            print(n, end = '')
    
        elif i == 2 and j == 1:
            print()
            print(n)
            
        elif i == 3 and j < 5:
            print(n, end = '')

        elif i == 4 and j == 1:
           print()
           print(n)

        elif i == 5 and j == 1:
           print(n)            
          
        elif i == 6 and j == 1:
            print(n)

Upvotes: 0

Views: 700

Answers (3)

luther
luther

Reputation: 5554

The default end argument for print is a newline ('\n'). Both the clauses in your code that print more than one asterisk get rid of the newline with end='' (an empty string). This leaves it up to the next clause to add a newline using print().

EDIT: Clarify what '' is.

Upvotes: 1

Safkat Arefin
Safkat Arefin

Reputation: 11

When you use this print(n, end = '') command it will print on the same row. To make it print on the next row you need to use print(). If you do not use print() it will continue to print on the same row.

Upvotes: 1

CoolCoder
CoolCoder

Reputation: 822

When you are printing a single asterisk, you just do print(n), where n="*".
Note, that when using the function print, it automatically inserts a newline character (\n) at the end, so that whenever you print something again, it comes on a newline.
But, this can be overridden by doing print(n, end=''). This does not put a newline character at the end, but puts the end character at the end.
So, now, the next print would not go to the next line, but continue on the same line.
So, when you want to print an asterisk on a new line, you need to do print(), which just prints a newline character and then the next print would print on a new line.

Upvotes: 1

Related Questions