The variable in the main function of Python defaults to a global variable , while the other variables in the DEF function default to local variables .
Of course, local variables take precedence over global variables , as can be seen when executing formal_print (T_global) statements.
The test code is as follows:
<span style= "FONT-SIZE:18PX;" > #coding =utf-8# Test python global variables, local variable mechanism def formal_print (S_global): #常规的传参用法, pass parameters to print, variable names can be arbitrarily print "Formal_ Print: ", S_global return def global_print (): #无参数传递, print print" Global_print: "directly to global variable, s_ Globaldef Global_print_para (ST): #此处虽然传递了一个参数st, but did not use print "Global_print_para:" In the function, S_globaldef Test_global (): stest = ' Test_global ' print "Test_global:", stest return if __name__ = = ' __main__ ': s_global = ' Glob Al variable s_global ' #main函数中声明的变量默认为global variable, while the variables declared in other DEF functions default to local variable t_global = ' global variable T_global ' formal_print (s_global) formal_print (T_global) global_print () Test_global () # The variable stest is declared in Formal_print (stest) #虽然在test_global (), but Stest is not a global variable, print ' End. ' </span>