Printing Simple Diamond Pattern in Python

后端 未结 15 2583
执笔经年
执笔经年 2020-12-19 23:14

I would like to print the following pattern in Python 3.5 (I\'m new to coding):

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


        
15条回答
  •  甜味超标
    2020-12-19 23:21

    Another possibility. Depending on which (space or star) one uses, (I used space) convert it to absolute value. This implementation doesn't require splitting the diamond into two loops (upper and lower halves).

    def diamond(n):
        star = 1
        main = ''
        # if required to manage zero or negative n
        if n%2 == 0:
            return None
        if n<0:
            return None
        else:
            for i in range(1,n+1):
                string = ''
                space = abs(i - int((n+1)/2))
                star = n - 2 * space
                string = space * ' ' + star * '*' + '\n'
                main += string
            # not necessary but useful to visualize diamond 
            #print(main)
            return(main)
    

提交回复
热议问题