【问题标题】:"while" loop exiting prematurely (python 3)“while”循环过早退出(python 3)
【发布时间】:2018-08-18 11:21:03
【问题描述】:

while 循环只运行一次并退出,就好像条件已经满足一样,但是,在调试外部是否满足条件时(循环之后)它没有。

这是我的代码:

iFile = open("snakein.txt")
line = iFile.readline()
finXStr,finYStr = line.split()

finX = int(finXStr)
finY = int(finYStr)



moves = []

snkX = 0
snkY = 0

while snkX != finX and snkY != finY:
    if finX > 0 and finX != snkX:
        moves.append("R")
        snkX += 1
        print("x moves")
    elif finX < 0 and finX != snkX:
        moves.append("L")
        snkX -= 1
        print("x moves")
    elif finX == snkX:
        moves.append("L")
        snkX -= 1
        print("x moves")
    if finY < 0 and moves[-1] == "R":
        moves.append("R")
        snkY -= 1
        print("y moves")
    elif finY < 0 and moves[-1] == "L":
        moves.append("L")
        snkY -= 1
        print("y moves")
    elif finY > 0 and moves[-1] == "R":
        moves.append("L")
        snkY += 1
        print("y moves")
    elif finY > 0 and moves[-1] == "L":
        moves.append("R")
        snkY += 1
        print("y moves")
    elif finY == snkY:
        moves.appebd("L")
        snakeY -= 1
        print("y moves")

output = moves

oFile = open("snakeout.txt", "w")
oFile.write(str(output))

该程序试图通过某些移动以最有效的方式使“蛇”移动到特定目标,在类似设置的“笛卡尔平面”上。

【问题讨论】:

  • 输入文件中有什么?在循环开始之前,finXfinY 是否具有您期望的值?
  • 是的,我已经检查过了
  • 这段代码sn-p不完整,因为你没有告诉我们文件snakein.txt的内容。请给我们一个完整的sn-p,我们可以根据How to create a Minimal, Complete, and Verifiable example运行。

标签: python


【解决方案1】:

看起来while snkX != finX or snkY != finY: 在您的上下文中可能更有意义...

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多