Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I run a script after importing it?

Problem

I would like to import a script containing many functions and then run them, so that I can use the function. I may have misunderstood the purpose of import. I am working in Jupyter.

Reprex

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#Create the script in a local folder

%%writefile test.py
c = 500

def addup(a,b,c):
    return a*b + (c)

#import the file and use it

import test
addup(1,5,c)


#Error message

---------------------------------------------------------------------------
# NameError                                 Traceback (most recent call last)
# <ipython-input-1-71cb0c70c39d> in <module>
#       1 import test
# ----> 2 addup(1,5,c)

# NameError: name 'addup' is not defined

Any help appreciated.

>Solution :

You have not called the function! You need a dot . to call a function from a module.

This is the correct syntax:

import test
result = test.addup(1,5,c)

Import a specific function:

from test import addup
addup(1,5,c)

Importing all of the module’s functions:

from test import *
addup(1,5,c) # this way you can use any function from test.py without the need to put a dot
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

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

Continue reading