需要幫助使用 python 創建聖誕樹

布里吉

我剛剛在我的大學開始了 Python 課程,需要幫助解決一個練習。它要求我編寫一個 Christmas_tree(h,n,s) 函數,該函數繪製帶有“*”字符的聖誕樹。該練習需要有一個

  • h:高度級別,樹的每一層的行數
  • n:級別數
  • s:在樹的每一層和下一層之間移動“*”的數量

前任。Christmas_tree(5,4,2) 將表示為:

在此處輸入圖片說明 在此處輸入圖片說明

山姆懷斯

使用兩個嵌套循環來處理級別和每個級別內的變化,並使用該str.center方法將每一行居中。

>>> def christmas_tree(h, n, s):
...     max_width = 1 + 2 * h * n
...     width = 1
...     for _ in range(n):
...         for _ in range(h):
...             print(("*" * width).center(max_width))
...             width += 2
...         width -= 2 * s
...
>>> christmas_tree(5, 4, 2)
                    *
                   ***
                  *****
                 *******
                *********
                 *******
                *********
               ***********
              *************
             ***************
              *************
             ***************
            *****************
           *******************
          *********************
           *******************
          *********************
         ***********************
        *************************
       ***************************

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章