缺少2个必需的位置参数'x'和'y'的函数

8

我正在尝试编写一个Python turtle程序来绘制Spirograph,但是我一直遇到这个错误:

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班上的一项练习,我不知道如何修复错误。

2个回答

9
追踪回溯信息的最后一行会告诉你问题出现在哪里。
  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),它们分别是Rrpxy。在错误信息中突出显示的那行代码中,你只传递了三个参数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

作为这个任务的一部分,其余的就由你来完成了。

1
错误提示您调用spirograph函数时使用的参数过少。
请更改以下代码:
while p<100 and p>10:
    goto(x,y)
    spirograph(R,r, p-1, x,y) # pass on  the missing R and r

尽管你没有使用这些参数,但你仍然需要将它们提供给函数以调用它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接