I'm very new to Python and trying to learn how classes, methods, scopes, etc works by building very silly programs with no real purpose.
The code I wrote below is suppose to just define a class Functions that is instantiated using an x and a y value and then one can execute various simple math functions like add subtract, multiply or divide (yes I know there is a Python Math library).
However, whenever I run my code and I get to the section where I want to run a math function in my class it runs the entire program over again and then does the math function.
What am I doing wrong here?
The file name is MyMath.py
class Functions():
def __init__(self, x, y):
self.x = x
self.y = y
def add(self):
return self.x+self.y
def subtract(self):
return self.x-self.y
def multiply(self):
return self.x*self.y
def divide(self):
return self.x/self.y
def check_input(input):
if input == int:
pass
else:
while not input.isdigit():
input = raw_input("\n " + input + " is not a number. Please try again: ")
return input
print("Welcome to the customzied Math program!")
x = raw_input("\nTo begin, please enter your first number: ")
x = check_input(x)
y = raw_input("Enter your second number: ")
y = check_input(y)
from MyMath import Functions
math = Functions(x,y)
print(math.add())
Remove the following statement.
from MyMath import Functions
The first line of the program defines the name Functions, and you can use it without having to import it. You only use the import command if the class (or function, or variable, ...) is defined in a different file/module.
Note in addition: When you import anything from a module the whole module is run as a script (although only the Functions name is imported into the local namespace). For this reason, everything within a file to be imported should be contained inside a class or function (unless there is a good reason not to...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With