Python 尝试在函数外部循环附加列表

Python 尝试在函数外部循环附加列表,python,python-3.x,function,Python,Python 3.x,Function,我试图完成下面的循环,其中输入来自用户,然后通过顶部的shipPlacement函数发送。但是,当我运行代码时,循环在shipSizeList中运行第一个术语,然后在完成函数后,不会提示用户输入另一个inputPos输入。我如何设计它,以便将所有不同大小的船舶位置附加到船舶列表中 listOfShipsPos = [] # adds to the grid where all of the ships are def shipPlacement(position,size,direction)

我试图完成下面的循环,其中输入来自用户,然后通过顶部的shipPlacement函数发送。但是,当我运行代码时,循环在shipSizeList中运行第一个术语,然后在完成函数后,不会提示用户输入另一个inputPos输入。我如何设计它,以便将所有不同大小的船舶位置附加到船舶列表中

listOfShipsPos = []

# adds to the grid where all of the ships are
def shipPlacement(position,size,direction):
    listOfShipsPos.append(position)
    direction.upper()
    i = 1
    # for the length of ship (size), repeats adding positions in the
    # desired direction (up(U), down(D), left(L) or right(R))
    while i < size:
        if direction == "U":
            listOfShipsPos.append(ship - 8)
        if direction == "D":
            listOfShipsPos.append(ship + 8)
        if direction == "L":
            listOfShipsPos.append(ship - 1)
        if direction == "R":
            listOfShipsPos.append(ship + 1)
        i =+ 1


# ask user to input their ship positions
shipSizeList = [2, 3, 3, 4, 5]
for shipSize in shipSizeList:
    inputSize = shipSize
    inputPos = int(input("Position for " + str(shipSize) + " sized ship? (1 to 64)"))
    inputDir = str(input("direction for " + str(shipSize) + " long ship? "))
    shipPlacement(position=inputPos, size=inputSize, direction=inputDir)
函数shipPlacement实际上从未完成执行,因为循环从未完成。原因是语句i=+1。它应该是i+=1。另外,我认为您应该重新分配变量方向,这是完整的代码

listOfShipsPos = []

# adds to the grid where all of the ships are
def shipPlacement(position,size,direction):

    listOfShipsPos.append(position)
    direction = direction.upper()
    i = 1
    # for the length of ship (size), repeats adding positions in the
    # desired direction (up(U), down(D), left(L) or right(R))
    while i < size:

        if direction == "U":
            listOfShipsPos.append(ship - 8)
        if direction == "D":
            listOfShipsPos.append(ship + 8)
        if direction == "L":
            listOfShipsPos.append(ship - 1)
        if direction == "R":
            listOfShipsPos.append(ship + 1)
        i += 1


# ask user to input their ship positions
shipSizeList = [2, 3, 3, 4, 5]
for shipSize in shipSizeList:
    inputSize = shipSize
    inputPos = int(input("Position for " + str(shipSize) + " sized ship? (1 to 64)"))
    inputDir = str(input("direction for " + str(shipSize) + " long ship? "))
    shipPlacement(position=inputPos, size=inputSize, direction=inputDir)

增广赋值应为“a+=1”。您的声明“a=+1”与“a=+1”相同,或者只是“a=1”。