Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set variable based on input by user?

I have some code where I want the inputted position to be replaced with the desired string but I can’t find a way for it to happen from input.

pos1 = ("_")
pos2 = ("_")
pos3 = ("_")
pos4 = ("_")
pos5 = ("_")
pos6 = ("_")
pos7 = ("_")
pos8 = ("_")
pos9 = ("_")

def board():
  print(pos1,pos2,pos3)
  print(pos4,pos5,pos6)
  print(pos5,pos6,pos9)  

while True:
  board()
  
  print("player one you are x\n")

  choice = input("player one enter a position.")

  choice = ("x")

I want to have the position that they choose replace the original variable. For example if the user inputs pos1 then the value of pos1 becomes "x".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think a dictionary is a good way to go here.

  1. First store the board represented in a dictionary (All positions are empty "_")
  2. Create a function for printing the board
  3. Ask the user for input and change the given position to "x" or "o"

Here is a code snippet:

# Initialize the board, represented as a dictionary
pos = {"pos1":"_",
       "pos2":"_",
       "pos3":"_",
       "pos4":"_",
       "pos5":"_",
       "pos6":"_",
       "pos7":"_",
       "pos8":"_",
       "pos9":"_",
       }


def board():
    # Function to print the current status of the board
    print(pos["pos1"],pos["pos2"],pos["pos3"])
    print(pos["pos4"],pos["pos5"],pos["pos6"])
    print(pos["pos7"],pos["pos8"],pos["pos9"])

# Run loop
while True:
    board()
    print("player one you are x\n")
    choice = input("player one enter a position.")
    pos[choice] = "x"   # Modify the board, by assigning an x to the players choice
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading