Getting started with Python: local variables

Source: Internet
Author: User

A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable.

The global variable scope is the entire program, and the local variable scope is the subroutine that defines the variable.

When a global variable has the same name as a local variable: Local variables work within subroutines that define local variables; global variables work elsewhere

Example 1:

def change_name (name):

Print ("Before Change", name)

Name= "Zhangyan" #这个函数就是这个变量的作用域

Print ("After Change", name)

Name= "Zhangyan"

Change_name (name)

Print (name)

Result: Name is still Zhangyan (reason: The local variable cannot modify the value of the global variable)

Example 2:

def change_name (name):

Age=28

Print (age)

Result: Error, age undefined

Example 3:

School= "Oldboy"

def change_name (name):

Global school #局部变量前加上global变为全局变量, you can modify the value of the same variable name outside the function

School= ' Mage Linux '

Print (school)

Result: School for "Mage Linux"

  

Getting started with Python: local variables

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.