Python程序打印空心倒金字塔星形图案

使用for循环、while循环和函数编写一个Python程序来打印空心倒金字塔星形图案。本例使用for循环迭代并打印空心倒金字塔星形图案。

rows = int(input("Enter Hollow Inverted Pyramid Pattern Rows = "))

for i in range(rows, 0, -1):
    for j in range(rows - i):
        print(end = ' ')
    for k in range(i):
        if (i == 1 or i == rows or k == 0 or k == i - 1):
            print('*', end = ' ')
        else:
            print(' ', end = ' ')
    print()

输出。

Python Program to Print Hollow Inverted Pyramid Star Pattern

此Python 程序while循环替换了上面的for循环,以打印空心倒金字塔星形图案。

rows = int(input("Enter Hollow Inverted Pyramid Pattern Rows = "))

i = rows
while i > 0:
    j = 0
    while j < rows - i:
        print(end = ' ')
        j = j + 1
    k = 0
    while k < i:
        if (i == 1 or i == rows or k == 0 or k == i - 1):
            print('*', end = ' ')
        else:
            print(' ', end = ' ')
        k = k + 1
    i = i - 1
    print()

输出

Enter Hollow Inverted Pyramid Pattern Rows = 9
* * * * * * * * * 
 *             * 
  *           * 
   *         * 
    *       * 
     *     * 
      *   * 
       * * 
        * 

在本例中,我们创建了一个HollowInvertedPyramid 函数,该函数接受行数和字符来打印空心倒金字塔图案。它用给定符号替换了空心倒金字塔图案中If else语句内的星号。

def HollowPyramid(rows, ch):
    for i in range(rows, 0, -1):
        for j in range(rows - i):
            print(end = ' ')
        for k in range(i):
            if (i == 1 or i == rows or k == 0 or k == i - 1):
                print('%c' %ch, end = ' ')
            else:
                print(' ', end = ' ')
        print()
    
rows = int(input("Enter Hollow Inverted Pyramid Pattern Rows = "))
ch = input("Symbol in Hollow Inverted Pyramid Pattern = ")

HollowPyramid(rows, ch)

输出

Enter Hollow Inverted Pyramid Pattern Rows = 13
Symbol in Hollow Inverted Pyramid Pattern = #
# # # # # # # # # # # # # 
 #                     # 
  #                   # 
   #                 # 
    #               # 
     #             # 
      #           # 
       #         # 
        #       # 
         #     # 
          #   # 
           # # 
            #