Python’s Turtle library is a fantastic tool for drawing graphics. In this article, we will explore how to create an interactive program that allows users to enter the number of sides for a polygon, and then draw that shape dynamically.
1. Step-by-Step Code Explanation.
Let’s examine the following Python script:
import turtle t = int(turtle.textinput('Sides', 'Enter the number of sides:')) turtle.circle(50, steps=t) turtle.done()
1.1 Importing the Turtle Library.
- Turtle is a built-in Python module that provides simple drawing functions. We need to import it before using it.
import turtle
1.2 Taking User Input.
- Below code will take user input as the number of sides to draw the shape.
t = int(turtle.textinput('Sides', 'Enter the number of sides:'))
- The `turtle.textinput(title, prompt)` function creates a pop-up window to take user input.
- Since the input is a string, we use `int()` to convert it into an integer.
1.3 Drawing a Polygon.
- Below code will draw a polygon based on the input parameters.
turtle.circle(50, steps=t)
- `turtle.circle(radius, steps=t)`:
- The `radius=50` defines the size.
- The `steps=t` determines how many edges the shape will have.
- If `t=3`, it will draw a triangle.
- If `t=4`, it will draw a square.
- If `t=100`, it will approximate a circle.
1.4 Keeping the Window Open.
- The below code prevents the drawing window from closing immediately.
turtle.done()
2. Conclusion.
- Turtle makes drawing easy and interactive.
- The `turtle.textinput()` function allows user input.
- Using `turtle.circle()` with `steps=t`, we can draw custom polygons.
- Using `turtle.done()` to keep the turtle window open.
3. Demo Video.
You can watch the following demo video by select the subtitle to your preferred subtitle language.