-6

iam making easy battleship game. but there is something that doesnt make sense for me. when there is strictly append in the first loop it has different output than if i wrote the same thing with variable..

import random

BOARD = []

for i in range(5):
    BOARD.append(["O"]*5)

x = random.randint(1,5)
y = random.randint(1,5)

while True:
    for i in BOARD:
        print(" ".join(i))

    row = int(input(": "))
    column = int(input(": "))

    if x == row and y == column:
        print("you win")
    else:
        BOARD[x - 1][y - 1] = "X"

in case of miss there is output like this

O O O O O
O X O O O
O O O O O
O O O O O
O O O O O

but if i wrote this code.. which is similar to previous.. only difference is a variable in the first loop... it has totaly different output..

import random

BOARD = []

Q = ["O"]*5

for i in range(5):
    BOARD.append(Q)

x = random.randint(1,5)
y = random.randint(1,5)

while True:
    for i in BOARD:
        print(" ".join(i))

    row = int(input(": "))
    column = int(input(": "))

    if x == row and y == column:
        print("you win")
    else:
        BOARD[x - 1][y - 1] = "X"

but there is output like this.. it doesnt make sense for me

O x O O O
O X O O O
O x O O O
O x O O O
O x O O O

is there on this site anyone who can explain this ??? nobody can help

SweepCore
  • 1
  • 2

1 Answers1

1

This must solve the issue:

import random

BOARD = []

Q = ["O"]*5

for i in range(5):
    BOARD.append(list(Q))

x = random.randint(1,5)
y = random.randint(1,5)

while True:
    for i in BOARD:
        print(" ".join(i))

    row = int(input(": "))
    column = int(input(": "))

    if x == row and y == column:
        print("you win")
    else:
        BOARD[x - 1][y - 1] = "X"

You must make copy of the list Q: BOARD.append(list(Q))