Python无效Int()E

2024-09-30 00:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

import turtle
index = 0 #to traverse through list
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')
outFile=inFile.read()
outFileContent = outFile.split ()
while index != (len(outFileContent)): #for item in the list
    if str(outFileContent [index]) == "UP": #if the current index goes up, pen up
        sammy.penup()

    elif str(outFileContent [index]) == "DOWN": #else if its down, pen down
        sammy.pendown ()

    elif outFileContent[index].isalpha () == False : #if its a number, go to 
those coordinates
        sammy.goto (int(outFileContent[index]),int(outFileContent[index+1])) #convert from str to int

    index+=1 #goes to next value in list


    print ((int(outFileContent [index]), int(outFileContent[index+1]))) #make sure its printing the right coordinates

inFile.close()
wn.mainloop ()

所以这个程序应该打开一个列表,然后让乌龟执行列表上的命令。如果线读上去了,乌龟就把笔竖起来。如果这行字写下来,乌龟就放下笔。如果这条线是一对数字,那么乌龟就去那些坐标系。以下是文件内容“神秘.txt“:

^{pr2}$

但是,当我运行程序时,它会输出:

Traceback (most recent call last):
File "C:\Users\Yariel\Google 
Drive\Coding\Python\Scripts\Files\turtle_file_mystery_shape.py", line 23, in <module>
print ((int(outFileContent [index]), int(outFileContent[index+1]))) #make 
sure its printing the right coordinates
ValueError: invalid literal for int() with base 10: 'DOWN'

我不知道为什么它会变成一个我从未指定过的整数。(如果查看print语句中的坐标,它将输出正确的坐标)。 有什么帮助吗?怎么解决这个问题?在


Tags: thetoinindexifinfilelistits
2条回答

我建议你重新考虑一下,而不是修补你的代码。下面的重做一行一行地处理这个神秘文件,而不是一次处理所有这些文件,希望您更容易扩充和调试:

import sys
from turtle import Turtle, Screen

screen = Screen()
# Set width of the drawing to 800px and height to 600px
screen.setup(800, 600)

sammy = Turtle()

commands = {'UP': sammy.penup, 'DOWN': sammy.pendown}

with open('mystery.txt') as inFile:

    for line in inFile:
        content = line.rstrip().split()

        if len(content) == 1 and content[0] in commands:

            commands[content[0]]()  # eg. UP and DOWN

        elif len(content) == 2 and not content[0].isalpha() and not content[1].isalpha():

            # seem to be numbers, convert from str to int and go to those coordinates
            sammy.goto(int(content[0]), int(content[1]))

        else:
            print("Invalid input:", content, file=sys.stderr)

screen.mainloop()

坐标是一种特殊的输入情况。您需要将index增加一个1,以容纳第二个int。在

# ...
elif outFileContent[index].isalpha () == False : #if its a number, go to those coordinates
    sammy.goto (int(outFileContent[index]),int(outFileContent[index+1])) #convert from str to int
    # move print to here; indexing changed
    print ((int(outFileContent [index]), int(outFileContent[index+1])))
    # additional increment to index to accommodate second int
    index += 1

index+=1 #goes to next value in list
# ...

相关问题 更多 >

    热门问题