Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีวาดรูปทรงต่างๆ ด้วยไลบรารี Turtle ของ Python


ในโปรแกรมนี้ เราจะวาดรูปทรงต่างๆ โดยใช้ Turtle Library ใน Python Turtle เป็นฟีเจอร์ของ Python คล้ายกระดานวาดภาพ ซึ่งให้คุณสั่งเต่าให้วาดทุกอย่างบนมัน รูปทรงที่เราจะวาดคือ สี่เหลี่ยมจัตุรัส, สี่เหลี่ยมผืนผ้า, วงกลม และหกเหลี่ยม

อัลกอริทึม

ขั้นตอนที่ 1: รับความยาวด้านสำหรับรูปทรงต่างๆ จากผู้ใช้

ขั้นตอนที่ 2: ใช้เมธอด Turtle ต่างๆ เช่น forward() และ left() สำหรับวาดรูปทรงต่างๆ

ตัวอย่างโค้ด

import turtle
t = turtle.Turtle()
#SQUARE
side = int(input("Length of side: "))
for i in range(4):
    t.forward(side)
    t.left(90)
#RECTANGLE
side_a = int(input("Length of side a: "))
side_b = int(input("Length of side b: "))
t.forward(side_a)
t.left(90)
t.forward(side_b)
t.left(90)
t.forward(side_a)
t.left(90)
t.forward(side_b)
t.left(90)
#CIRCLE
radius = int(input("Radius of circle: "))
t.circle(radius)
#HEXAGON
for i in range(6):
    t.forward(side)
    t.left(300)

ผลลัพธ์

SQUARE: Length of side: 100 วิธีวาดรูปทรงต่างๆ ด้วยไลบรารี Turtle ของ PythonRECTANGLE: Length of side a: 100 Length of side b: 20 วิธีวาดรูปทรงต่างๆ ด้วยไลบรารี Turtle ของ PythonCIRCLE: Radius of circle: 60 วิธีวาดรูปทรงต่างๆ ด้วยไลบรารี Turtle ของ PythonHEXAGON:Length of side: 100 วิธีวาดรูปทรงต่างๆ ด้วยไลบรารี Turtle ของ Python