How To Take User Input and Draw Custom Polygons in Python

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.

  1. 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.

  1. 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:'))
  2. The `turtle.textinput(title, prompt)` function creates a pop-up window to take user input.
  3. Since the input is a string, we use `int()` to convert it into an integer.

1.3 Drawing a Polygon.

  1. Below code will draw a polygon based on the input parameters.
    turtle.circle(50, steps=t)
  2. `turtle.circle(radius, steps=t)`:
  3. The `radius=50` defines the size.
  4. The `steps=t` determines how many edges the shape will have.
  5. If `t=3`, it will draw a triangle.
  6. If `t=4`, it will draw a square.
  7. If `t=100`, it will approximate a circle.

1.4 Keeping the Window Open.

  1. The below code prevents the drawing window from closing immediately.
    turtle.done()

2. Conclusion.

  1. Turtle makes drawing easy and interactive.
  2. The `turtle.textinput()` function allows user input.
  3. Using `turtle.circle()` with `steps=t`, we can draw custom polygons.
  4. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top