因此,文件mystery.txt的行包含单词UP或DOWN或一对数字。上和下是乌龟抬起或放下其笔的说明。这对数字是一些x,y坐标。mystery.txt的前几行是
UP
-218 185
DOWN
-240 189
-246 188
-248 183
错误是在我的else语句中说:
sammy.goto(wordList[i],wordList[i+1])
我想知道为什么在这种情况下不应该使用[i + 1]以及如何解决它。下面是我的代码...
import turtle
turtle.setup(800,600) # Change the width of the drawing to 800px and the height to 600px.
wn = turtle.Screen()
sammy = turtle.Turtle()
inFile = open('mystery.txt','r')
fileString = inFile.read() # read entire file into a string
inFile.close() # we're done with the file, so we can close it now
wordList = fileString.split()
for i in range(len(wordList)):
if str(wordList[i]) == "UP":
sammy.penup()
elif wordList[i] == "DOWN":
sammy.pendown()
else:
sammy.goto(wordList[i],wordList[i+1])
i += 1
错误直接在else语句之后的代码的第15行上。错误状态:
IndexError: list index out of range on line 15
这是一种更清洁的方法。
我们一步一步地遍历文件的每一行,并在读取文件时对其进行处理。
当我们有一条坐标线时,我们将其拆分并将值转换为int。
import turtle
turtle.setup(800,600) # Change the width of the drawing to 800px and the height to 600px.
wn = turtle.Screen()
sammy = turtle.Turtle()
with open('mystery.txt','r') as inFile: # using with will take care of closing the file, whatever happens
for line in inFile: # read and treat the file line by line
line = line.strip() # remove the trailing '\n'
if line == "UP":
sammy.penup()
elif line == "DOWN":
sammy.pendown()
else:
# we have a pair of coordinates, we split the line and convert the coords to int
x, y = map(int, line.split())
sammy.goto(x, y)
请注意,在大多数情况下,在Python中进行迭代时不需要使用索引,这样可以避免遇到的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句