Draw a Sine wave using Turtle in Python

Draw a Sine wave using Turtle in Python

Drawing a sine wave using the Turtle graphics library in Python is a fun way to visualize trigonometric functions. Turtle graphics provide an interactive way to draw shapes and patterns. To draw a sine wave, you'll need to use the turtle module and some basic trigonometry.

Here's a Python script to draw a sine wave using Turtle:

import turtle import math # Set up the screen screen = turtle.Screen() screen.setup(800, 600) # Create a turtle wave_drawer = turtle.Turtle() wave_drawer.speed(0) # Move the turtle to the starting point wave_drawer.penup() wave_drawer.setpos(-390, 0) wave_drawer.pendown() # Draw a sine wave for x in range(-390, 390): y = 100 * math.sin((x / 100) * 2 * math.pi) # Scale and calculate sine value wave_drawer.setpos(x, y) # Hide the turtle and finish wave_drawer.hideturtle() # Keep the window open screen.mainloop() 

In this script:

  • The turtle.Screen() creates a window for the drawing.
  • A turtle.Turtle() object, wave_drawer, is created to do the drawing.
  • The sine wave is drawn by iterating over a range of x-values, calculating the corresponding y-value using the sine function, and moving the turtle to each (x, y) position.
  • The sine function is scaled to fit the screen nicely. You can adjust the scaling factor and the range of x-values as needed.

Run this script in a Python environment where Turtle graphics are supported (like a local IDE). The script will open a window and draw a sine wave.


More Tags

slideshow frontend econnrefused text-widget querying string-matching items bootstrap-5 function verify

More Programming Guides

Other Guides

More Programming Examples