用python打印菱形的實操方法和代碼
更新時間:2019年06月25日 15:29:42 投稿:laozhang
在本篇文章里小編給大家分享了關(guān)于用python打印菱形的實操方法和代碼,對此有需要的朋友們可以學習下。
python怎么打印菱形?下面給大家?guī)砣N方法:
第一種
rows = int(input('請輸入菱形邊長:\n')) row = 1 while row <= rows: col = 1 # 保證每次內(nèi)循環(huán)col都從1開始,打印前面空格的個數(shù) while col <= (rows-row): # 這個內(nèi)層while就是單純打印空格 print(' ', end='') # 空格的打印不換行 col += 1 print(row * '* ') # 每一行打印完空格后,接著在同一行打印星星,星星個數(shù)與行數(shù)相等,且打印完星星后print默認換行 row += 1 bottom = rows-1 while bottom > 0: col = 1 # 保證每次內(nèi)循環(huán)col都從1開始,打印前面空格的個數(shù) while bottom+col <= rows: print(' ', end='') # 空格的打印不換行 col += 1 print(bottom * '* ') # 每一行打印完空格后,接著在同一行打印星星,星星個數(shù)與行數(shù)相等,且打印完星星后print默認換行 bottom -= 1
輸出結(jié)果:
請輸入菱形邊長: 5 * * * * * * * * * * * * * * * * * * * * * * * * *
第二種
s = '*' for i in range(1, 8, 2): print((s * i).center(7)) for i in reversed(range(1, 6, 2)): print((s * i).center(7))
輸出結(jié)果:
* *** ***** ******* ***** *** *
第三種
def stars(n): RANGE1 = [2*i+1 for i in range(n)] RANGE2 = [2*i+1 for i in range(n)[::-1]][1:] RANGE = RANGE1 + RANGE2 RANGE_1 = [i for i in range(n)[::-1]] RANGE_2 = [i for i in range(n)[1:]] RANGE_12 = RANGE_1 + RANGE_2 for i in range(len(RANGE)): print (' '*RANGE_12[i] + '*'*RANGE[i]) if __name__ == "__main__": stars(5)
輸出結(jié)果:
* *** ***** ******* ********* ******* ***** *** *
以上就是關(guān)于用python來畫出菱形的方法總結(jié),感謝大家的閱讀和對腳本之家的支持。
相關(guān)文章
使用Python的Django和layim實現(xiàn)即時通訊的方法
這篇文章主要介紹了使用Python的Django和layim實現(xiàn)即時通訊的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05詳解Python解決抓取內(nèi)容亂碼問題(decode和encode解碼)
這篇文章主要介紹了Python解決抓取內(nèi)容亂碼問題(decode和encode解碼),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-03-03python MNIST手寫識別數(shù)據(jù)調(diào)用API的方法
這篇文章主要介紹了python MNIST手寫識別數(shù)據(jù)調(diào)用API的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08