将列表元素传递给函数

时间:2018-04-26 21:52:33

标签: python turtle-graphics

我有一个我写的模块,其中包含一个收集大量输入的函数,并将它们附加到列表中。该模块还包含一堆需要使用list元素的已定义的turtle函数。但是,我在乌龟函数上遇到语法错误。这是给我错误的确切函数(其他龟函数也是类似的):

def draw_circle(turtle, shape_info[5]):
   turtle.circle(shape_info[5])

列表元素5是用户先前在第一个函数中输入的长度输入。我究竟做错了什么?

错误是这样的:

Traceback (most recent call last):
File "C:\Users\ebarr\OneDrive\Programming\MIS 3300\MIS 3300\hw6.py", line 6, 
in <module>
import hw6util
File "C:\Users\ebarr\OneDrive\Programming\MIS 3300\MIS 3300\hw6util.py", line 122
def draw_circle(evan, shape_info[5]):
                                ^
SyntaxError: invalid syntax

2 个答案:

答案 0 :(得分:2)

您可能希望执行以下操作:

# the function takes the list element type as the argument
def draw_circle(turtle, info):
   turtle.circle(info)

 user_length = 5; # index of the length in shape_info
 # we call the function using the indexed element into the list
 draw_circle(turtle, shape_info[user_length])

答案 1 :(得分:1)

这不是有效的函数定义:

def draw_circle(turtle, shape_info[5]):

你可能想要的是:

def draw_circle(turtle, shape_info):
    turtle.circle(shape_info[5])

或许这个:

def draw_circle(turtle, shape_info_5th):
    turtle.circle(shape_info_5th)

...然后使用shape_info[5]而不是shape_info来调用它。