Python inverted hollow pyramid second row

Question:

I have a code:

r = int(input("Length of upper base of triangle = "))

print("Hollow Inverted Right Triangle Star Pattern") 

for i in range(1, r + 1):
    for j in range(1, 2*r):
        if (i == 1 and not j%2 == 0) or i == j or i + j == r*2:
            print('*', end = '')
        else:
            print(' ', end = '')
    print()

After the command I get:

* * * * * * * * * * *
 *                 * 
  *               *  
   *             *   
    *           *    
     *         *     
      *       *      
       *     *       
        *   *        
         * *         
          * 

I wanted to modify the code to print star every second row, i. e.

* * * * * * * * * * *
  
  *               *

    *           *

      *       *

        *   *

          *

How to do this? It looks like the code needs a simple modification but I don’t get it.

Asked By: Malum Wolfram

||

Answers:

What you want to do is to skip printing stars on every second line by printing a blank line and then continuing the loop.

You can use the modulus operator (%) to check if a line is even, and then skip that run of the loop.

r = int(input("Length of upper base of triangle = "))

print("Hollow Inverted Right Triangle Star Pattern") 

for i in range(1, r + 1):
    if i%2 == 0:
        print()
        continue
    for j in range(1, 2*r):
        if (i == 1 and not j%2 == 0) or i == j or i + j == r*2:
            print('*', end = '')
        else:
            print(' ', end = '')
    print()

Answered By: DeathPacito6
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.