Python Program to import variables from another file

When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working. It can be done by having separate files for different working codes. As we know, various libraries in Python provide various methods and variables that we access using simple import <library_name>. For example, math library. If we want to use the pi variable we use import math and then math.pi.

To import variables from another file, we have to import that file from the current program. This will provide access to all the methods and variables available in that file.

The import statement

We can use any Python source file as a module by executing an import statement in some other Python source file. When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches for importing a module.

Python is a high-level programming language that allows the use of modules to import variables, functions, and classes from one Python script to another. This helps to avoid duplicating code and make it easier to manage large projects. In this article, we will discuss how to import variables from another file in Python.

To import variables from another file, we need to create a Python module with the desired variables that we want to import. A Python module is a file that contains Python definitions and statements.

Let's create a simple Python module called example_module.py with the following code: 

 

x = 10
y = "Hello, World!"

To import these variables from the example_module.py file, we need to use the import keyword in our main Python script as follows: 

 

import example_module

print(example_module.x)
print(example_module.y)

Here, we have imported the example_module and accessed its variables x and y using the . operator.

We can also import specific variables from the example_module.py file using the from keyword as follows: 

 

from example_module import x, y

print(x)
print(y)

Here, we have imported only the variables x and y from the example_module using the from keyword.

In conclusion, importing variables from another file in Python is a straightforward process that involves creating a Python module and using the import or from keyword in our main Python script.

Submit Your Programming Assignment Details