【问题标题】:Why does "turtle.pd" produce a syntax error in my Python code?为什么“turtle.pd”会在我的 Python 代码中产生语法错误?
【发布时间】:2020-04-05 21:27:17
【问题描述】:

我试图制作一种复杂的参数化绘图仪,但这并不重要。重要的是我的程序应该使用 Turtle 图形绘制一个圆圈,当我放下笔时,“turtle.pd()”行出现语法错误。我不知道是怎么回事。你们能帮帮我吗?我的程序在下面。

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)

【问题讨论】:

  • try 需要except。一般来说,如果您在某个意外的地方收到 SyntaxError,请查看上一行/块以查看您是否忘记关闭某些内容,例如) 或在本例中为 except
  • 不能解决问题
  • “不能解决问题”不是一个有用的回答。请阅读How to Ask。您对代码做了什么确切的更改?
  • 为什么try 会出现在首位?

标签: python python-3.x turtle-graphics python-turtle


【解决方案1】:

除了@dguis 指出的缺少的except 子句语法错误(+1),我想知道您认为这些行在做什么:

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

如果.xcor.ycor 是你自己的属性,你已经隐藏在一个turtle 实例上,那么没关系。如果你认为这会移动乌龟——那么不会。如果目标是移动海龟,请尝试:

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

带有额外调整的完整解决方案:

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)

【讨论】:

    【解决方案2】:

    我会添加

    except [errortype]:
        pass
    

    try 块之后。将 [errortype] 替换为您希望通过 try 块减少的错误。我看不出该块内可能会引发什么错误,您可能只是写了

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

    并一起删除 try 块。

    【讨论】:

    • 你为什么只在except 块中使用pass?为什么try 还在那里?如果不了解上下文并知道要防止什么,您就无法推荐一个好的异常处理策略。
    • 是的,这就是为什么我还建议他们可以一起删除 try-except 块。我知道传入 except 块是愚蠢的,但 @WilliamPowell 可以将 pass 更改为他们想要的任何其他内容。
    猜你喜欢
    • 2015-05-10
    • 2020-10-18
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    相关资源
    最近更新 更多