參考:雙迴圈5*5實心方塊
範例一、用函式來實現雙迴圈5*5實心方塊
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import turtle def square(c): c.begin_fill() c.forward(100) c.left(90) c.forward(100) c.left(90) c.forward(100) c.left(90) c.forward(100) c.left(90) c.end_fill() c = turtle.Turtle() for i in range(1,6): for j in range(-2,3): c.penup() c.goto(-500+i*150,j*150) c.pendown() c.color("red") square(c) |
執行結果:
範例二、預設長度的參數
執行結果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import turtle def square(c, length=100): c.begin_fill() c.forward(length) c.left(90) c.forward(length) c.left(90) c.forward(length) c.left(90) c.forward(length) c.left(90) c.end_fill() c = turtle.Turtle() for i in range(1,6): for j in range(-2,3): c.penup() c.goto(-500+i*150,j*150) c.pendown() c.color("red") square(c,80) |
範例三、增加顏色參數
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import turtle def square(c, length=100, color="red"): c.color(color) c.begin_fill() c.forward(length) c.left(90) c.forward(length) c.left(90) c.forward(length) c.left(90) c.forward(length) c.left(90) c.end_fill() c = turtle.Turtle() for i in range(1,6): for j in range(-2,3): c.penup() c.goto(-500+i*150,j*150) c.pendown() square(c,80, "blue") |
執行結果:
範例四、增加位置參數
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import turtle def square(c, length=100, color="red", pos_x=-650, pos_y=0): c.penup() c.goto(pos_x,pos_y) c.pendown() c.color(color) c.begin_fill() c.forward(length) c.left(90) c.forward(length) c.left(90) c.forward(length) c.left(90) c.forward(length) c.left(90) c.end_fill() c = turtle.Turtle() for i in range(1,6): for j in range(-2,3): square(c,80, "blue", -400+i*100,j*100) |
執行結果:
範例五:宣告主程式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import turtle def square(c, length=100, color="red", pos_x=-650, pos_y=0): c.penup() c.goto(pos_x,pos_y) c.pendown() c.color(color) c.begin_fill() c.forward(length) c.left(90) c.forward(length) c.left(90) c.forward(length) c.left(90) c.forward(length) c.left(90) c.end_fill() def main(): c = turtle.Turtle() for i in range(1,6): for j in range(-2,3): square(c,80, "blue", -400+i*100,j*100) if __name__ == "__main__": main() |
執行結果:
同上題
沒有留言:
張貼留言