What happens when you modify variables inside a function in Python

Source: Internet
Author: User

Recently writing Python encountered a problem with an internal variable using an external variable, now summarize it.

#!/usr/bin/env python

A = 100
def SU ():
A = a + 1
Print (a)

s = SU ()

#执行这段代码会报错 (if only the call is not modified will not be an error)

Change to:

#!/usr/bin/env python

A = 100
def SU ():
Global A
A = a + 1
Print (a)

s = SU ()

Summarize:

In Python's function and the global variable with the same name, if the value of the modified variable becomes a local variable,

A reference to the variable before it is modified will naturally occur without the definition of such an error,

If you are sure that you want to reference a global variable, and you want to modify it, you must add the Global keyword.

What happens when you modify variables inside a function in Python

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.