SyntaxError: name ‘x‘ is assigned to before global declaration

created at 08-18-2021 views: 425

error descritpion

code:

import os
import math
import sys

MAX = 0

if __name__ == '__main__':
    global MAX
    MAX = 9

error message:

SyntaxError: name ‘MAX‘ is assigned to before global declaration

solution

You need to modify the value of the global variable MAX in the main function, but the main function and the global variable MAX belong to the same context, so there is no need to use global here. After correction:

import os
import math
import sys

MAX = 0

def ch():
     global MAX # Need to use global
     MAX = 9

if __name__ =='__main__':
     # global MAX does not need to use global here
     MAX = 9
created at:08-18-2021
edited at: 08-18-2021: