简体   繁体   中英

Why does “turtle.pd” produce a syntax error in my Python code?

I was trying to make a sort-of complex parametric grapher, but that isn't what's important. What's important is that my program is supposed to draw a circle using Turtle graphics, and when I put the pen down, I have a syntax error in the " turtle.pd() " line. I have no idea what's going on. Can you guys help me? My program is below.

import turtle, math, cmath
def f(x): return math.e ** (1j * x) # Use Python code to define f(x) as the return value; don't forget the math and cmath modules are imported
precision = 25 # This program will draw points every (1 / precision) units
def draw(x):
    value = f(x)
    try:
        turtle.xcor = value.real * 25 + 100
        turtle.ycor = value.imag * 25 + 100
    turtle.pd() # Syntax error here
    turtle.forward(1)
    turtle.pu()
draw(0)
num = 0
while True:
    num += 1
    draw(num)
    draw(-num)

I would add

except [errortype]:
    pass

after the try block. Replace [errortype] with the error that you hoped to reduce with the try block. I don't see what error could be raised within that block, to you could likely just write

turtle.xcor = value.real * 25 + 100
turtle.ycor = value.imag * 25 + 100

and remove the try block all together.

Besides the missing except clause syntax error that @dguis points out (+1), I wonder what you think these lines are doing:

turtle.xcor = value.real * 25 + 100
turtle.ycor = value.imag * 25 + 100

If .xcor and .ycor are your own properties that you've stashed on a turtle instance, then it's OK. If you think this moves the turtle -- then not. If the goal is to move the turtle, try:

turtle.setx(value.real * 25 + 100)
turtle.sety(value.imag * 25 + 100)

Complete solution with additional tweaks:

import turtle
import math

def f(x):
    return math.e ** complex(0, x)

def draw(x):
    value = f(x) * 25

    turtle.setx(value.real + 100)
    turtle.sety(value.imag + 100)

    turtle.pendown()
    turtle.forward(1)
    turtle.penup()

turtle.penup()

num = 0

draw(num)

while True:
    num += 1
    draw(num)
    draw(-num)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM