Malum Wolfram
Malum Wolfram

Reputation: 19

Python inverted hollow pyramid second row

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.

Upvotes: 0

Views: 210

Answers (1)

DeathPacito6
DeathPacito6

Reputation: 26

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()

Upvotes: 1

Related Questions