首页 > 解决方案 > if语句没有在python的while循环中运行

问题描述

我在运行一些用于在井字游戏中输入的代码时遇到了问题。代码编写如下:

def player_input():
marker = " "

while marker != "X" and marker != "O":
    marker = input("Player 1: Do you want me to play X or O? ").upper()

if marker == "X":
    return ("X", "O")
else:
    return ("O", "X")
    

玩家输入()

调用函数后,'if loop' 没有在文本编辑器中运行,而在 Jupyter notebook 中,代码返回元组,我不明白为什么!需要帮忙。我是初学者。

标签: tic-tac-toe

解决方案


You have missed the line indentations..And you didnt mention the method outside the code..

Line Indentations: In simple terms indentation refers to adding white space before a statement. But the question arises is it even necessary? To understand this consider a situation where you are reading a book and all of a sudden all the page numbers from the book went missing. So you don’t know, where to continue reading and you will get confused. This situation is similar with Python. Without indentation, Python does not know which statement to execute next or which statement belongs to which block.

Revised version of code....

def player_input():
    marker = "  "
    while marker != "X" and  marker != "O":
        marker = input("Player do you want to play X or O").upper()
        if marker   == "X":
            print("You have chosen X and if statement works...Insert your command here")
        else:
            print("You have chosen O and else statement works...Insert your command here")
        
player_input()

推荐阅读