为什么我的文件代码有错误?

RM13

因此,文件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
蒂埃里·拉图耶(Thierry Lathuille)

这是一种更清洁的方法。

我们一步一步地遍历文件的每一行,并在读取文件时对其进行处理。

当我们有一条坐标线时,我们将其拆分并将值转换为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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么此代码有错误?

为什么我的.bashrc有错误?

为什么我在此代码中收到“您的 SQL 语法有错误”错误?

Google kickstart 2022 为什么我的代码第 11 行有错误

为什么`cargo build`不能在我的代码中显示所有错误?

我的代码有错误

为什么发布的Java源代码中有错误?

为什么下面的代码编译没有错误?

为什么以下Java代码中有错误?

为什么这行Java代码有错误?

为什么我有错误“[Header] 不是 <Route> 组件。”?

为什么我有错误的输出java headfirst?

Scala-使用DFS检测周期吗?我的代码有错误,我似乎无法弄清楚为什么

为什么我的代码有IllegalStateException错误

Windows 10中的文件ini_set在哪里我为什么在这个脚本中有错误

我的SQL代码有错误

我的 PHP 代码有错误

我的代码有什么问题,因为没有错误,但是我无法运行它?

JQuery Ajax,为什么成功了我有错误为什么?

为什么此列表有错误?

我现在没有,为什么我在这个 sql 请求中有错误

我想拆分和重命名大量文件。我的代码有错误

我的代码有什么问题?程序直接终止,没有错误语句

编译时没有错误代码,但屏幕上没有数据表,我无法弄清为什么

为什么我收到“您的 SQL 语法有错误”错误?

我没有错误,但为什么我的应用程序闭上

为什么此代码有“内联文件中的EOF”错误,我该如何解决?

为什么下面的代码编译时没有错误?

为什么C标准允许此代码编译时没有错误?