Python determines if a variable exists

Source: Internet
Author: User
Tags vars

When a variable is called, if the variable is not defined, then Python will make an error.

The method to be solved is also very simple, which is to assign a null value to the variable beforehand.

However, you can also call the system's built-in function to determine whether a variable name has been defined. There are 3 built-in functions that can be implemented.

res1 = ' Test ' in locals (). Keys () Res2 = ' Test ' in dir () Res3 = ' Test ' in VARs (). Keys () print (RES1,RES2,RES3) # variable test not yet defined , return falsetest = "" # define variable testres4 = ' Test ' in locals (). Keys () res5 = ' Test ' in dir () res6 = ' Test ' in VARs (). Keys () print (res 4,RES5,RES6) # variable test has been defined, returns true

Above, you can use the above function to add a judgment if you encounter a variable that is not sure whether you have defined it.


Python determines if a variable exists

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.