Reputation: 1
So I have a program with a module and a seperate file which are as follows Module:
def area_of_Triangle(b, h, units = "square centimeters"):
aot = (b * h) / 2
return "{0} {1}".format(aot, units)
def MyTuple(*args):
result = 0
for arg in args:
result += arg
return result
divide = lambda x, y: x / y if y != 0 else "Not Allowed"
The separate file:
import MODULE1
print (area_of_Triangle(4.5, 5.6, units="square inches"))
print (MyTuple(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
print (divide(2, 3))
every time I try to run it, it keeps saying name 'area_of_Triangle' not defined
Upvotes: 0
Views: 93
Reputation:
You've to write MODULE1.area_of_triange(<parameters>)
and print it. Or else if you don't want to write MODULE1 again and again, you can import specific function from the module, or import all functions using from MODULE1 import *
line and then directly use the functions without writing the module name again and again
Upvotes: 0
Reputation: 59
you only imported the module using
import Module1
if you want to import all methods and variables in a python file use the * sign
for example
from <modulename> import *
so in your case it would be
from Module1 import *
or alternatively, you can import a specific method by using the same way but instead of * use the method's name
for example
from Module1 import area_of_Triangle
if you do not wish to do the above
import Module1
is also fine, just have to call the method as such:
Module1.area_of_Triangle(4.5, 5.6, units="square inches")
notice the Module1.area_of_Triangle()
Upvotes: 0
Reputation: 374
You're trying to call MODULE1 functions from a different file. You either need to specify MODULE1 in the calls
import MODULE1
print (MODULE1.area_of_Triangle(4.5, 5.6, units="square inches"))
print (MODULE1.MyTuple(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
print (MODULE1.divide(2, 3))
Or you can explicitly import them
from MODULE1 import area_of_Triangle, MyTuple, divide
print (area_of_Triangle(4.5, 5.6, units="square inches"))
print (MyTuple(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
print (divide(2, 3))
Why the extra hassle? Well what if you imported both MODULE1 and some MODULE2, and both define a function called area_of_Triangle
? How do you distinguish which is which?
Upvotes: 2