How to Import other Python files in a Program

Hello Learners, today we are going to learn how to import other Python files in a program. It is easy to import other files in your Python code. It just takes one or two steps and there you go!

See the image, here we have two files, wlcm.py and wlcm main.py

Python files

This is wlcm.py file. The file contains two methods named as hello and greet. but when you’ll try to execute this file, nothing will be printed because we haven’t call these methods yet.

def hello():
    print("Hey there!")

def greet(name):
    print("Hello {}, Welcome to CodeSpeedy!".format(name))

This is wlcm main.py file. In this file, we have imported the wlcm.py file to use its methods.

import wlcm

wlcm.hello()
wlcm.greet(input())

Now when you execute this file, you can see the output on console like this:

OUTPUT:

Hey there!
xyz
Hello xyz, Welcome to CodeSpeedy!

NOTE: both the files, the one you are trying to import, and the other that you are executing should be present in the same directory.

Suppose, you don’t want to import the entire file, you just need one method to use in your code. We can do that as well, Look at the editor below.

from wlcm import hello

hello()
greet("xyz")

OUTPUT:

Hey there!
Traceback (most recent call last):
File "C:\Users\lenovo\Documents\wlcm main.py", line 10, in <module>
greet("xyz")
NameError: name 'greet' is not defined
  • Here you have imported just the hello method only, So it gets executed. but when you try to call greet method, it will give you an error that greet is not defined because neither you imported it nor you defined it.

While creating big projects developers write the code in the modules. Modularization doesn’t only allow you to make manageable code but also increases code reusability and code readability.

Now you can try it on your own and see how the code works, make multiple functions and use them in the other codes by just importing them, it’s fun! Click on the link to learn more about Python Modules. So, that’s all for now about how to import other Python files in a program.

Leave a Reply

Your email address will not be published. Required fields are marked *