Can we change name==main with a def

Hello everybody,
I am new to python and I like to analyze codes to better understand the code. Here is the code I am currently analyzing:

def display_board(board):
    blankBoard="""
___________________
|     |     |     |
|  7  |  8  |  9  |
|     |     |     |
|-----------------|
|     |     |     |
|  4  |  5  |  6  |
|     |     |     |
|-----------------|
|     |     |     |
|  1  |  2  |  3  |
|     |     |     |
|-----------------|
"""

    for i in range(1,10):
        if (board[i] == 'O' or board[i] == 'X'):
            blankBoard = blankBoard.replace(str(i), board[i])
        else:
            blankBoard = blankBoard.replace(str(i), ' ')
    print(blankBoard)

def player_input():
    player1 = input("Please pick a marker 'X' or 'O' ")
    while True:
        if player1.upper() == 'X':
            player2='O'
            print("You've choosen " + player1 + ". Player 2 will be " + player2)
            return player1.upper(),player2
        elif player1.upper() == 'O':
            player2='X'
            print("You've choosen " + player1 + ". Player 2 will be " + player2)
            return player1.upper(),player2
        else:
            player1 = input("Please pick a marker 'X' or 'O' ")

def place_marker(board, marker, position):
    board[position] = marker
    return board

def space_check(board, position):
    return board[position] == '#'

def full_board_check(board):
    return len([x for x in board if x == '#']) == 1

def win_check(board, mark):
    if board[1] == board[2] == board[3] == mark:
        return True
    if board[4] == board[5] == board[6] == mark:
        return True
    if board[7] == board[8] == board[9] == mark:
        return True
    if board[1] == board[4] == board[7] == mark:
        return True
    if board[2] == board[5] == board[8] == mark:
        return True
    if board[3] == board[6] == board[9] == mark:
        return True
    if board[1] == board[5] == board[9] == mark:
        return True
    if board[3] == board[5] == board[7] == mark:
        return True
    return False

def player_choice(board):
    choice = input("Please select an empty space between 1 and 9 : ")
    while not space_check(board, int(choice)):
        choice = input("This space isn't free. Please choose between 1 and 9 : ")
    return choice

def replay():
    playAgain = input("Do you want to play again (y/n) ? ")
    if playAgain.lower() == 'y':
        return True
    if playAgain.lower() == 'n':
        return False

if __name__ == "__main__":
    print('Welcome to Tic Tac Toe!')
    i = 1
    # Choose your side
    players=player_input()
    # Empty board init
    board = ['#'] * 10
    while True:
        # Set the game up here
        game_on=full_board_check(board)
        while not game_on:
            # Player to choose where to put the mark
            position = player_choice(board)
            # Who's playin ?
            if i % 2 == 0:
                marker = players[1]
            else:
                marker = players[0]
            # Play !
            place_marker(board, marker, int(position))
            # Check the board
            display_board(board)
            i += 1
            if win_check(board, marker):
                print("You won !")
                break
            game_on=full_board_check(board)
        if not replay():
            break
        else:
            i = 1
            # Choose your side
            players=player_input()
            # Empty board init
            board = ['#'] * 10

The problem is that I don’t understand the usefulness of name==main which is located towards the end of the code. So my question is if we can replace this with a “def sth():”.
Thanks in advance for your help,
Qwartyx

Hello, @qwartyx, and welcome to Python Foundation Discourse!

The document, __main__ — Top-level code environment. will provide you with some background on this topic.

Essentially, the code in the block headed by the following will run if you execute the Python file directly:

if __name__ == "__main__":

If, instead, you import the file as a module, the code from the block will not run automatically, but you will have access to the top-level names defined by that module. For example, you will be able to call the functions defined therein.

In answer to your question about defining a function, sth(), you could import the module into another Python program, and use it as follows:

from tictactoe import *
def sth():
    print("Let's play Tic Tac Toe!")
    i = 1
    # Choose your side
    players=player_input()
    # Empty board init
    board = ['#'] * 10
    while True:
        # Set the game up here
        game_on=full_board_check(board)
        while not game_on:
            # Player to choose where to put the mark
            position = player_choice(board)
            # Who's playing?
            if i % 2 == 0:
                marker = players[1]
            else:
                marker = players[0]
            # Play !
            place_marker(board, marker, int(position))
            # Check the board
            display_board(board)
            i += 1
            if win_check(board, marker):
                print("You won and are now the Tic Tac Toe champion!")
                break
            game_on=full_board_check(board)
        if not replay():
            break
        else:
            i = 1
            # Choose your side
            players=player_input()
            # Empty board init
            board = ['#'] * 10

sth()

The original module would reside in a file named tictactoe.py.

Note that, just as one example of how the module could be used, nearly all the code in the above was copied from a portion of the original file, with some minor customization. It was placed in a function block, then the function was called.

You would now have the flexibility to customize the code further within the sth() function block, so that the program would behave markedly differently from the original, while you still have access to the functions defined in the module. For example, you could run a Tic Tac Toe tournament.

While in this example, some code was copied from the original file, you could instead choose to import the module, and subsequently write code from scratch, however you see fit, that includes calls to functions from the module.

EDITED 2x on April 3, 2022 to make minor adjustments to the text.

Ok, thanks for your answer, you help me a lot !

1 Like

The code:

if __name__ == "__main__":

checks whether the special global variable __name__ (two leading and two trailing underscores) is the string "__main__". If it is, it runs the TicTacToe game.

If the file you are reading is called “tictactoe.py”, then there are two ways you can use it:

  • run the file as a script;

  • or import it as a module.

If you run the file as a script, like this:

# give this command from the operating system shell
python tictactoe.py

or any similar method, the interpreter sets the global variable to the string "__main__", and so the above test will run the game.

But if you import the file as a module, like this:

# give this command from another Python script
import tictactoe

then the global variable will be set to “tictactoe”, and the game won’t be played.

In other words, this global variable __name__ can be used for Python code to distinguish when it is being run as a script or application.

What you can do is move all the code under the if __name__ == "__main__": line into a function, and then run the test:

def run_game():
    print('Welcome to Tic Tac Toe!')
    i = 1
    # Choose your side
    players=player_input()
    # Empty board init
    board = ['#'] * 10
    while True:
        # Set the game up here
        game_on=full_board_check(board)
        while not game_on:
            # Player to choose where to put the mark
            position = player_choice(board)
            # Who's playin ?
            if i % 2 == 0:
                marker = players[1]
            else:
                marker = players[0]
            # Play !
            place_marker(board, marker, int(position))
            # Check the board
            display_board(board)
            i += 1
            if win_check(board, marker):
                print("You won !")
                break
            game_on=full_board_check(board)
        if not replay():
            break
        else:
            i = 1
            # Choose your side
            players=player_input()
            # Empty board init
            board = ['#'] * 10

if __name__ == "__main__":
    run_game()

Of course you can use any name you want, but it is best to use a meaningful name. What does “sth” mean? If it has no meaning, you should use a better name like “run_game”.