NOTE: I’m a beginner programmer!
I came here with a problem – the string is not changing after request.
That’s my code:
row1 = ["⬜️","⬜️","⬜️"]
row2 = ["⬜️","⬜️","⬜️"]
row3 = ["⬜️","⬜️","⬜️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
position_str = str(position)
first = position_str[:1]
second = position_str[1]
first = int(first)-1
second = int(second)-1
if first == 1:
map[second][1] = "X"
elif first == 2:
map[second][2] = "X"
elif first == 3:
map[second][3] = "X"
print(f"{row1}\n{row2}\n{row3}")
And sure, when I type any number in between 21-23, 31-33 it’s changing, but when I type 11, 12, or 13 it’s not.
Can someone please help me?
>Solution :
The problem is that you translate the user’s input from 1-3 to 0-2 here:
first = int(first)-1
second = int(second)-1
but in the remainder of your code you assume that the values are still from 1-3:
if first == 1:
map[second][1] = "X"
elif first == 2:
map[second][2] = "X"
elif first == 3:
map[second][3] = "X"
Here’s a fixed version of the code that uses consistent indexing and also eliminates a lot of the copying and pasting. Note that naming a variable map is bad because it prevents you from using the very useful builtin map function!
treasure_map = [[" " for _ in range(3)] for _ in range(3)]
print("\n".join(map(str, treasure_map)))
position = input("Where do you want to put the treasure? ")
x, y = (int(n) - 1 for n in position)
treasure_map[y][x] = "X"
print("\n".join(map(str, treasure_map)))