簡體   English   中英

函數缺少2個必需的位置參數:'x'和'y'

[英]Function missing 2 required positional arguments: 'x' and 'y'

我正在嘗試編寫一個繪制Spirograph的Python龜程序,我不斷收到此錯誤:

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) ,它們是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

由於這是一個分配,其余由你決定。

該錯誤告訴您,您使用的參數太少而無法調用spirograph

更改此代碼:

while p<100 and p>10:
    goto(x,y)
    spirograph(R,r, p-1, x,y) # pass on  the missing R and r

你沒有使用這些參數,但你仍然必須將它們交給函數來調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM