如何在先前设置的打印文本中有一个变量?

2024-09-28 19:30:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python制作一个noughts和crosss游戏,我忘记了如何在打印的代码中包含一个变量。我知道我可以通过合并OX部分来提高代码的效率,但是使用变量来实现函数的零和交叉。 我目前所做的:

for i in range (1,2):
player = int(input("Select from either `O` [1] or `X` [2]: "))
while player <0 or player >2:
    print("You must only enter 1 for noughts, or 2 for crosses.")
    time.sleep (0.5)
    user = int(input("Select from either `O` [1] or `X` [2]: "))
else:
    if player==1:
        user="O"
        time.sleep (0.25)
        print("Player 1 has selected to be `O`.") #user has chosen to be noughts
        time.sleep (1)
        print(" ")
        time.sleep (0.5)
        print(" You can choose a square by entering in the co-ordinates of it. ")
        time.sleep (1.5)
        print(" EG: If you selected (2,1) and you were `O`, the grid would look like: ")
        time.sleep (1.5)
        print("  (x>) [1] {2} [3]")
        print("      ┌-----------┐")
        print("  {1} |   | O |   |")
        print("      |---+---+---|")
        print("  [2] |   |   |   |")
        print("      |---+---+---|")
        print("  [3] |   |   |   |")
        print(" (y^) └-----------┘")
        print(" ")
    else:
        user="X"
        time.sleep (0.25)
        print("Player 1 has selected to be `X`.") #user has chosen to be crosses
        time.sleep (1)
        print(" ")
        time.sleep (0.5)
        print(" You can choose a square by entering in the co-ordinates of it. ")
        time.sleep (1.5)
        print(" EG: If you selected (2,1) and you were `X`, the grid would look like: ")
        time.sleep (1.5)
        print("  (x>) [1] {2} [3]")
        print("      ┌-----------┐")
        print("  {1} |   | X |   |")
        print("      |---+---+---|")
        print("  [2] |   |   |   |")
        print("      |---+---+---|")
        print("  [3] |   |   |   |")
        print(" (y^) └-----------┘")
        print(" ")

    time.sleep(1.5)
    print("Tutorial over, time to play!")
    time.sleep(0.5)
    x_axis=float(input("Please enter the x-axis: "))
    y_axis=float(input("Please enter the y-axis: "))

我想是这样的,不对,我知道,请帮忙! user=xprint(" [3] | | {} | |".format{user}


Tags: orthetoyouinputtimesleepbe
1条回答
网友
1楼 · 发布于 2024-09-28 19:30:45

对于初学者,我建议只将变量添加到print()函数中,例如:

x = 3
print("I have", x, "apples")

但是,使用.format()更具可读性,如您的问题:

user=x 
print("  [3] |   | {}  |   |".format{user}

这应该在中间列中打印x

相关问题 更多 >