Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing a certain shape with python

I need to print a shape that looks like the following

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

I’ve tried doing this but only managed to print an X shape

n = 7
for i in range(0, n):
    for j in range(0, n):
        if (i==j or j==n-1-i):
            print("*",end=" ")
        else:
            print(" ",end=" ")

    print()

output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Don’t know how to approach this and would like some help 🙂 🙏

>Solution :

You can create two lists with the number of spaces before the first * and the number between the two *s and then use zip() and f-strings:

before = [0, 0, 1, 2, 1, 0, 0]
between = [3, 3, 1, 0, 1, 3, 3]
for i, j in zip(before, between):
    print(f'{i*" "}*{j*" "}{"*" if j  else ""}')

Output:

*   *
*   *
 * *
  *
 * *
*   *
*   *
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading