Python local variables and global variables scope--021

Source: Internet
Author: User
Tags define local

Global vs. local variables

1. Variables defined in subroutines are called local variables, and variables defined at the beginning of a program are called global variables.

2, the scope of global variables is the entire program, the scope of the local variable is the subroutine that defines the variable.

3. When the global variable has the same name as a local variable: Local variables work within subroutines that define local variables, and global variables work in other places.

Example one: (local variable)

def changename (name):    print ("Change before", name)    name = "Robin Wen"     #这个函数就是这个变量的作用域, this variable only takes effect in this function = = >> local variable    print ("Change after", name) name = "Robin" ChangeName (name) print

  

#我们使用上面的函数将robin传入函数中进行修改为Robin Wen, but the effect of the final output is still robin.

Output Result:

Change before Robin

Change after Robin Wen

Robin

Example two: (global variable)

Referencing global variables in a function program

School = "Oldboy" Def Stu ():    Global School    Print ("Before the school is:", school)    school = "BJ" Stu () print (" After the school is: ", school)

  

Python local variables and global variables scope--021

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.