The Calculator Program
This is a simple demonstration of a program that acts like a calculator.
The main point of this program is to demonstrate that all the functionality of the calculator that does that hard work is stored in the module calc.py
.
We then import calc.py
using the import statement:
import calc
This allows the main program to then use the functions that are defined (written) in main.py
The tests should just pass if you run them.
Main File
# main.py
# importing module calc (calc.py)
import calc
def main():
choice = None
print("Welcome to the Calculator...")
print(f"Did you know the value of Pi is approximately {calc.pi}")
while choice != "0":
print("""
What would you like to do?
1. Add
2. Subtract
3. Multiply
4. Divide
5. Power
6. Nth Root
""")
choice = input("")
if choice in ["1", "2", "3", "4", "5"]:
x = float(input("Please enter the first number:\n"))
y = float(input("Please enter the second number:\n"))
if choice == "1":
ans = calc.add(x,y)
elif choice == "2":
ans = calc.subtract(x,y)
elif choice == "3":
ans = calc.multiply(x,y)
elif choice == "4":
ans = calc.divide(x,y)
elif choice == "5":
ans = calc.power(x,y)
if ans:
print(f"Answer: {ans}")
else:
print("Division by 0 is illegal")
elif choice == "6":
x = float(input("Please enter the first number:\n"))
n = int(input("Please enter a whole value for n (nth root):\n"))
ans = calc.root(x,n)
print(f"Answer: {ans}")
else:
print("Invalid Option")
if __name__ == "__main__":
main()
Calc Module
# calc.py
pi = 3.14159
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x,y):
return x*y
def divide(x,y):
if not y == 0:
return x/y
else:
return None
def power(x,y):
return x**y
def root(x,y, epsilon=0.001):
if x < 0 and y % 2 == 0:
return None
low = min(-1.0, x)
high = max(1.0, x)
ans = (high + low) / 2.0
# check if the answer is close enough
while abs(ans**y - x) >= epsilon:
if ans**y < x:
low = ans
else:
high = ans
ans = (high + low) / 2.0
return ans