pythonif-statement

Python, elif caused problem while else didn't


my code didnt show error but it didnt show what I expected. It is a code to mark "X" on a 3x3 table. Here is the code

as far as I believe it is ok to just use elif multiple times instead of else

my code didnt show error but it didnt show what I expected. When I changed my code just last elif to else, It worked. Like I changed the corresponding code for input of "B3"


line1 = ["⬜️","️⬜️","️⬜️"]
line2 = ["⬜️","⬜️","️⬜️"]
line3 = ["⬜️️","⬜️️","⬜️️"]
map = [line1, line2, line3]
print("Hiding your treasure! X marks the spot.")
position = input() 


if position[0]=="A":
  if position[1]==1:
    line1[0]="X"
  elif position[1]==2:
    line2[0]="X"
  elif position[1]==3:
    line3[0]="X"

elif position[0]=="B":
  if position[1]==1:
    line1[1]="X"
  elif position[1]==2:
    line2[1]="X"
  else:
    line3[1]="X"

elif position[0]=="C":
  if position[1]==1:
    line1[2]="X"
  elif position[1]==2:
    line2[2]="X"
  elif position[1]==3:
    line3[2]="X"


print(f"{line1}\n{line2}\n{line3}")



Solution

  • The problem is not the if-statements. The input is saved as a string. if postition[1] == 1 therefore compares a string with an integer. Adjust the variables accordingly and it should work.

    You can make 'position[1]' an integer:

    if int(position[1]) == 1:
    

    or compare 'position[1]' with a string:

    if position[1] == "1":