昨天講完迴圈馬上就來練習一下,今天要做的這個練習相信大家在初學的時候一定會做,就是繪製星號三角形。
layer = 10
i = 0
while i < layer:
print(" " * (layer-i-1) + "*" * (i+1))
i = i + 1
'''
會顯示下面這樣
*
**
***
****
*****
******
*******
********
*********
**********
'''
這還可以寫成一個更整齊的版本。
把原本print裏的空格變成變數內容,這樣如果你需要換成其他符號時可以更輕易找到並且修改。
left, right = " ", "*"
layer = 10
i = 0
while i < layer:
left_count = layer - i - 1
right_count = i + 1
print(left * left_count + right * right_count)
i = i + 1
其實找到它的規律之後就可以很輕易的把它變形,我再放幾個變形的練習,你也可以自己找找看有沒有什麼更簡單的寫法喔。
left, right = " ", "*"
layer = 10
i = 0
while i < layer:
left_count = i
right_count = layer - i
print(left * left_count + right * right_count)
i = i + 1
'''
會顯示下面這樣
**********
*********
********
*******
******
*****
****
***
**
*
'''
left, mid, right = " ", "*", " "
layer = 10
i = 0
while i < layer:
lcount = layer - i - 1
mcount = 2 * i + 1
rcount = lcount
print(left * lcount +
mid * mcount +
right * rcount)
'''
會顯示下面這樣
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
'''
left, mid, right = " ", "*", " "
layer = 10
i = 0
while i < layer:
lcount = layer - i - 1
mcount = 2
rcount = i
print(left * lcount +
mid * mcount +
right * rcount)
i = i + 1
'''
會顯示下面這樣
**
**
**
**
**
**
**
**
**
**
'''
好了那今天就到這裡吧,自己玩玩看是不是發現蠻好玩的呢~