turtle.setx() function in Python
turtle.setx() method moves the turtle to a specified x-coordinate while keeping its current y-coordinate and heading (direction) unchanged. If the pen is down, it will draw a line from the current position to the new x-coordinate, if the pen is up, it moves without drawing.
Syntax:
turtle.setx(x)
- Parameters: x (int | float) is the x-coordinate to move the turtle to.
- Returns: This method only changes the turtle's horizontal position on the screen.
Examples of turtle.setx() function
Example 1: Simple horizontal movement
import turtle
turtle.setx(100)
turtle.done()
Output:

Explanation: The turtle moves directly to the x-coordinate 100 while keeping the same y-position, drawing a line if the pen is down.
Example 2: Moving left and right
import turtle
t = turtle.Turtle()
t.setx(100) # Move right
t.setx(-100) # Move left
turtle.done()
Output:

Explanation: The turtle first moves right to x = 100, then left to x = -100, keeping the same y-position.
Example 3: Move without drawing
import turtle
t = turtle.Turtle()
t.pendown()
t.setx(50)
t.penup()
t.setx(150)
turtle.done()
Output:

Explanation: The first move is done with the pen down (drawing a line), the second move is done with the pen up (no line drawn).