python - 函数缺少 2 个必需的位置参数 : 'x' and 'y'

标签 python turtle-graphics

我正在尝试编写一个绘制螺旋图的 Python turtle 程序,但我不断收到此错误:

Traceback (most recent call last):
  File "C:\Users\matt\Downloads\spirograph.py", line 36, in <module>
    main()
  File "C:\Users\matt\Downloads\spirograph.py", line 16, in main
    spirograph(R,r,p,x,y)
  File "C:\Users\matt\Downloads\spirograph.py", line 27, in spirograph
    spirograph(p-1, x,y)
TypeError: spirograph() missing 2 required positional arguments: 'x' and 'y'
>>> 

这是代码:

from turtle import *
from math import *
def main():
    p= int(input("enter p"))
    R=100
    r=4
    t=2*pi
    x= (R-r)*cos(t)-(r+p)*cos((R-r)/r*t)
    y= (R-r)*sin(t)-(r+p)*sin((R-r)/r*t)
    spirograph(R,r,p,x,y)


def spirograph(R,r,p,x,y):
    R=100
    r=4
    t=2*pi
    x= (R-r)*cos(t)-(r+p)*cos((R-r)/r*t)
    y= (R-r)*sin(t)-(r+p)*sin((R-r)/r*t)
    while p<100 and p>10:
        goto(x,y)
        spirograph(p-1, x,y)

    if p<10 or p>100:
        print("invalid p value, enter value between 10 nd 100")

    input("hit enter to quite")
    bye()


main()

我知道这可能有一个简单的解决方案,但我真的不知道我做错了什么,这是我计算机科学 1 课上的练习,我不知道如何修复错误。

最佳答案

回溯的最后一行告诉你问题出在哪里:

  File "C:\Users\matt\Downloads\spirograph.py", line 27, in spirograph
    spirograph(p-1, x,y) # <--- this is the problem line
TypeError: spirograph() missing 2 required positional arguments: 'x' and 'y'

在您的代码中,spirograph() 函数有 5 个参数:def spirograph(R,r,p,x,y),它们是 R rpxy。在错误消息中突出显示的行中,您只传递了三个参数 p-1, x, y,由于这与函数预期的不匹配,Python 会引发错误。

我还注意到您正在覆盖函数主体中的一些参数:

def spirograph(R,r,p,x,y):
    R=100 # this will cancel out whatever the user passes in as `R`
    r=4 # same here for the value of `r`
    t=2*pi

这是一个简单的例子:

>>> def example(a, b, c=100):
...    a = 1  # notice here I am assigning 'a'
...    b = 2  # and here the value of 'b' is being overwritten
...    # The value of c is set to 100 by default
...    print(a,b,c)
...
>>> example(4,5)  # Here I am passing in 4 for a, and 5 for b
(1, 2, 100)  # but notice its not taking any effect
>>> example(9,10,11)  # Here I am passing in a value for c
(1, 2, 11)

由于您始终希望将此值保留为默认值,因此您可以从函数的签名中删除这些参数:

def spirograph(p,x,y):
    # ... the rest of your code

或者,您可以给它们一些默认值:

def spirograph(p,x,y,R=100,r=4):
    # ... the rest of your code

因为这是一个任务,剩下的由你决定。

关于python - 函数缺少 2 个必需的位置参数 : 'x' and 'y' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18940249/

相关文章:

python - 不明白此 AttributeError : '_Screen' object has no attribute 'setimage' 的原因

python - 为 PyQt5 QCalendarWidget 单元格着色并打印单元格内的数据

python - 为什么我只能在异步函数中使用await关键字?

python - 如何在当前行的开头显示竖线?

python - 如何在 Django 中为每个应用程序的静态文件创建单独的文件夹

python - python中的多重递归是如何工作的

python - python 中的缩放功能? (2.7.9)

python - 可变性、局部性和循环

python - 在两个连续执行的函数之间添加延迟

python - Turtle.Screen().screensize() 未输出正确的屏幕尺寸