The variables in the Python main function default to global variable

Source: Internet
Author: User

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>


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.