def triangel(): print ' '*(20*3)+str(1) #定義起始兩行 print ' '*(19*3)+str(1)+' '*5+str(1) for i in range(3,21): if i ==3: L = [1,1] #初始化第二行 L1 = [] for j in range(2,i): z = L[i-j-1]+L[i-j] # 通過上一行構建下一層數據 L1.append(z) # 將數據添加到一個空列表中 L = [1] # 再次對L初始化 L.extend(L1) # 將兩個列表合並 L.append(1) # 在L列表中添加最后一個數據“1” # 以下內容為楊輝三角的打印 t = ' '*((21-i)*3)+str(1) # 每次循環進行初始化每列的第一個數據1 for h in range(1,len(L)): # 以下為構建每列的除一個數據外的其他數據, if L[h]<10: # 如果數據小於10,就是其前面5個空格,如果 t = t + ' '*5+str(L[h]) #數據小於100,就減少一個空格,依次類推, elif L[h] <100: # 直至剩余一個空格,用於分辨相鄰的數據 t = t+' '*4+str(L[h]) elif L[h] < 1000: t = t + ' '*3+str(L[h]) elif L[h] < 10000: t = t + ' '*2+str(L[h]) elif L[h] < 100000: t = t + ' '*1+str(L[h]) print t
以下是運行效果圖: