The ChessAIThon project (2025-1-ES01-KA220-VET-000354329) is co-funded by the European Union. The views and opinions expressed in this publication are those of the author(s) only and do not necessarily reflect those of the European Union or the Spanish Service for the Internationalisation of Education (SEPIE). Neither the European Union nor the National Agency SEPIE can be held responsible for them.
Table of Contents
Variables declared inside a function are called local variables: they can be used only within the function body. Once the function finishes executing, they are no longer accessible from outside.
Variables defined outside functions are called global variables. A function can freely read their content; however, if it needs to modify them (i.e., assign a new value), it must explicitly declare inside the function that it intends to refer to the global variable using the global keyword followed by its identifier. Otherwise, an assignment to that identifier will create a local variable with the same name, leaving the global variable unchanged.
The following code defines a global variable named turn, initialized with the string "White", which represents the player whose turn it is to move. Next, the print_turn() function is defined; it simply reads and prints the value of the turn variable, which is accessible inside the function because it is global.
# global variable
turn = "White"
def print_turn():
# Read the global variable: this is allowed without using 'global'
print(f"It is {turn} turn")
print_turn()
Output: It is White turn
The following code also defines a global variable called turn, again initialized with the value "White". Next, the change_turn() function is defined. The first statement in its body is global turn: this declaration explicitly states that the identifier turn, inside the function, refers to the global variable rather than to a new local variable. As a result, the assignment turn = "Black" actually modifies the global variable, replacing "White" with "Black".
# global variable
turn = "White"
def change_turn():
global turn
if turn == "White":
turn = "Black"
else:
turn = "White"
print(f"Before calling the function, turn = {turn}")
change_turn()
print(f"After calling the function, turn = {turn}")
Output:
Before calling the function, turn = White
After calling the function, turn = Black