简体   繁体   中英

Can someone help me to make this diamond shape with loop? (Python)

n=3
   *
  * *
 *   *
  * *
   *

n=5
    *    
   * *
  *   *
 *     *
*       *
 *     *
  *   *
   * *
    *

I tried this but I don't use n=3 or n=5

for row in range(5):
    for col in range(5):
        if row+col==2 or col-row==2 or row-col==2 or row+col==6:
            print("*",end="")
        else:
            print(end=" ")
    print()

And when I run it

  *  
 * *
*   *
 * *
  *

I need to make diamond shape with loop, but I'm really new to python, can someone help me? Thanks in advance!

Here's the general form of this function, which takes n and produces diamonds that match the two shown in the question, and all other sizes as well:

def diamond(n):
    print("n=" + str(n))
    nn = 2 * n - 1
    for row in range(nn):
        for col in range(nn):
            if row+col==n-1 or col-row==n-1 or row-col==n-1 or row+col==3*(n-1):
                print("*",end="")
            else:
                print(end=" ")
        print()

diamond(3)
diamond(5)
diamond(7)

Result:

n=3
  *  
 * * 
*   *
 * * 
  *  
n=5
    *    
   * *   
  *   *  
 *     * 
*       *
 *     * 
  *   *  
   * *   
    *    
n=7
      *      
     * *     
    *   *    
   *     *   
  *       *  
 *         * 
*           *
 *         * 
  *       *  
   *     *   
    *   *    
     * *     
      *      

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM