BenjaminT
BenjaminT

Reputation: 65

Importing function to new file not working

My program is designed to create a module named MyTriangle that reads three sides of a triangle and computes the area if the input is valid. If the input is invalid, it will display "Input is invalid". The program works beautifully. The only problem is that I am trying to import module (everything except the main function) over into a different file. I have never done this before, and can't find anywhere that gives clear instructions. Here is my code:

side1, side2, side3 = eval(input("Enter three sides in a double: "))

def isValid(side1, side2, side3):

    return side1 + side2 > side3 and side1 + side3 > side2 and side2 + side3 > side1 

def area(side1, side2, side3):

    s = (side1 + side2 + side3) / 2;

    totalArea = (s * (s - side1) * (s - side2) * (s - side3)) ** 0.5    

    return totalArea

def main():  

    condition = isValid(side1, side2, side3)

    totalArea = area(side1, side2, side3)

    if condition:
        print("The area of the triangle is " + str(totalArea))
    else:
        print("input is invalid")

main()

I tried taking the "def main()" part and putting that into a file by itself. While naming the file with all the rest of the code "MyTriangle.py"

import MyTriangle
def main():  

    condition = isValid(side1, side2, side3)

    totalArea = area(side1, side2, side3)

    if condition:
        print("The area of the triangle is " + str(totalArea))
    else:
        print("input is invalid")

main()

When I run the program, it asks "Enter three sides in a double:". When I put the numbers in (for example: 1, 1, 1), it says "name 'isValid' is not defined. I am not sure if I am importing it over correctly or what. For the life of me, I cannot figure this out. A little help please?

Upvotes: 0

Views: 183

Answers (1)

zondo
zondo

Reputation: 20336

When you say import myTriangle, you are defining myTriangle as the other module. Variables defined in that module are accessed as attributes of myTriangle. You can use myTriangle.isValid(...) instead of isValid(...). Alternatively, you could say from myTriangle import * instead of import myTriangle. Using from myTriangle import * puts all variables defined in myTriangle into the local namespace so that they can be accessed without putting myTriangle at the beginning.

Upvotes: 2

Related Questions