【问题标题】:How to set variable based on input by user?如何根据用户输入设置变量?
【发布时间】:2022-06-29 22:36:38
【问题描述】:

我有一些代码希望将输入的位置替换为所需的字符串,但我找不到从输入中发生的方法。

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")

我想让他们选择的位置替换原始变量。例如,如果用户输入pos1,则pos1 的值变为"x"

【问题讨论】:

  • 是否应该保留过去的选择,即过去在董事会的位置?还是应该在每次迭代时清除板子?

标签: python


【解决方案1】:

我认为dictionary 是一个不错的选择。

  1. 首先将表示的棋盘存储在字典中(所有位置为空"_"
  2. 创建用于打印电路板的函数
  3. 要求用户输入并将给定位置更改为“x”或“o”

这是一个代码sn-p:

# 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2011-01-14
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多