python - Importing function to new file not working -
my program designed create module named mytriangle reads 3 sides of triangle , computes area if input valid. if input invalid, display "input invalid". program works beautifully. problem trying import module (everything except main function) on different file. have never done before, , can't find anywhere gives clear instructions. here code:
side1, side2, side3 = eval(input("enter 3 sides in double: ")) def isvalid(side1, side2, side3): return side1 + side2 > side3 , side1 + side3 > side2 , 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 triangle " + str(totalarea)) else: print("input invalid") main()
i tried taking "def main()" part , putting file itself. while naming file rest of code "mytriangle.py"
import mytriangle def main(): condition = isvalid(side1, side2, side3) totalarea = area(side1, side2, side3) if condition: print("the area of triangle " + str(totalarea)) else: print("input invalid") main()
when run program, asks "enter 3 sides in double:". when put numbers in (for example: 1, 1, 1), says "name 'isvalid' not defined. not sure if importing on correctly or what. life of me, cannot figure out. little please?
when import mytriangle
, defining mytriangle
other module. variables defined in module accessed attributes of mytriangle
. can use mytriangle.isvalid(...)
instead of isvalid(...)
. alternatively, from mytriangle import *
instead of import mytriangle
. using from mytriangle import *
puts variables defined in mytriangle
local namespace can accessed without putting mytriangle
@ beginning.
Comments
Post a Comment