Skip to content

Python call function from another file

  • by

Simply you have to import the function from another file using the import keyword and then call the function in Python.

First, import function from file.py:

from file import function

Later, call the function using:

function(a, b)

Note: 1. That file is one of Python’s core modules, so change the filename of file.py to something else.
2. if you’re trying to import functions from a.py to a file called b.py, you will need to make sure that a.py and b.py are in the same directory.

Python call function from another file example

A simple example code calls a function from another py file.

main.py

import MathMethod as MM

print(MM.Add(200, 1000))

print(MM.subtract(1000, 500))

MathMethod.py

def Add(a,b):
return a+b

def subtract(a,b):
return a-b

Output:

Python call function from another file

Do comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading