为什么我的方法只在 while 循环中第一次运行?

Why my method only runs the first time in a while loop?

提问人:Carlos Chaires 提问时间:3/30/2023 更新时间:3/30/2023 访问量:40

问:

我正在尝试用 turtle 和 pandas 库做一个测验,所以我放了一个 while 循环运行 50 次,文本输入运行良好,但方法只运行了第一次,我不知道为什么,我已经在网上搜索但没有成功。

这是在主 Python 文件上。

import turtle
from List import State

screen = turtle.Screen()
screen.title("Quizz U.S. States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
states = State()
guessed_states = []

while len(guessed_states) < 50:
    answer_state = screen.textinput(f"{len(guessed_states)}/50 Guess the State",
                                    "Whats another state's name? ").title()
    if states.check_if_exists(answer_state):
        guessed_states.append(answer_state)
        states.print_state(answer_state)

这是我的班级列表

def check_if_exists(self, a_state):
    if a_state in self.states_list:
        return True

def print_state(self, a_state):
    self.states_list = data[data.state == a_state]
    self.t.goto(int(self.states_list.x), int(self.states_list.y))
    self.t.write(f"{self.states_list.state.item()}", align=ALIGNMENT, font=FONT)

问题是只运行第一次,如果将加利福尼亚的打印件放在正确的目的地,但如果继续写状态,它就不再显示。

每次我在文本提示中放下一个州时,如果在州列表中,我想在地图上打印其名称。

python-3.x 方法 while-loop turtle-graphics

评论

2赞 Alex V. 3/30/2023
你能分享一下列表的其余部分吗?
0赞 Pumba 3/30/2023
你能在控制台中打印 while 循环中guessed_states的结果吗?
0赞 Carlos Chaires 3/30/2023
@Alex诉这是我列表的其余部分import pandas from turtle import Turtle # reading the csv file data = pandas.read_csv("50_states.csv") # splitting into states states_list = data["state"].to_list() # Constants ALIGNMENT = "center" FONT = ("Consolas", 10, "bold") class State: def __init__(self): self.t = Turtle() self.t.penup() self.t.hideturtle() self.t.color("black") self.states_list = data["state"].to_list()
0赞 Alex V. 3/30/2023
我在 print_state 中收到错误,因为 self.states_list.x 不存在。你是说self.states_list[“x”]吗?如果您的终端中出现任何错误,请分享它们,因为它们确实有助于调试。
0赞 ggorlen 3/30/2023
@CarlosChaires最好编辑您的帖子以显示大块代码。很难将其解读为评论。

答:

0赞 Alex V. 3/30/2023 #1

在print_state中,重新定义self.states_list并尝试调用 self.states_list.x 和 self.states_list.y,它们不是现有属性。self.states_list.state.item() 也不是现有的方法。发布问题时,请始终添加运行代码时收到的错误消息。请务必阅读 pandas 数据帧以及如何访问特定元素。

我稍微修改了您的代码以使其有效。它现在检查字符串是否确实是有效状态。如果是,并且尚未找到,它将调用 print_state,但现在它将从 DataFrame 中获取 x 和 y 坐标,而无需更改 self.states_list 变量。

import turtle
import pandas
from turtle import Turtle
# reading the csv file
data = pandas.read_csv("50_states.csv")
# splitting into states
states_list = data["state"].to_list()
# Constants
ALIGNMENT = "center"
FONT = ("Consolas", 10, "bold")


class State:
    def __init__(self):
        self.t = Turtle()
        self.t.penup()
        self.t.hideturtle()
        self.t.color("black")
        self.states_list = data["state"].to_list()
        print(self.states_list)

    def check_if_exists(self, a_state):
        if a_state in self.states_list:
            return True

    def print_state(self, a_state):
        # Get the row index for the state that was found.
        index = data[data['state'] == a_state].index[0]
        # Get the coordinates for that state
        coords = [data["x"][index], data["y"][index]]
        # Go to the coordinates
        self.t.goto(int(coords[0]), int(coords[1]))
        # Write the state name
        self.t.write(f"{a_state}", align=ALIGNMENT, font=FONT)


screen = turtle.Screen()
screen.title("Quizz U.S. States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
states = State()
guessed_states = []

while len(guessed_states) < 50:
    answer_state = screen.textinput(f"{len(guessed_states)}/50 Guess the State",
                                    "Whats another state's name? ").title()

    if states.check_if_exists(answer_state):
        if answer_state in guessed_states:
            print("You have already guesses that one!")
            continue
        guessed_states.append(answer_state)
        states.print_state(answer_state)
    else:
        print('Wrong answer.')

也许可以尝试稍微重构您的代码,以便您拥有一个 Quiz 类,而不是您目前使用的 State 类。 您可以将找到的状态存储在 Quiz 类本身中,并删除状态列表的多个副本。