93 lines
2.8 KiB
Python
93 lines
2.8 KiB
Python
"""
|
|
Scientific Calculator
|
|
A simple command-line calculator supporting arithmetic, trigonometric, and logarithmic operations.
|
|
"""
|
|
|
|
import math
|
|
|
|
def add(x, y):
|
|
"""Return the sum of x and y."""
|
|
return x + y
|
|
|
|
def subtract(x, y):
|
|
"""Return the difference of x and y."""
|
|
return x - y
|
|
|
|
def multiply(x, y):
|
|
"""Return the product of x and y."""
|
|
return x * y
|
|
|
|
def divide(x, y):
|
|
"""Return the quotient of x and y."""
|
|
if y == 0:
|
|
raise ValueError("Cannot divide by zero.")
|
|
return x / y
|
|
|
|
def sine(x):
|
|
"""Return the sine of x (in radians)."""
|
|
return math.sin(x)
|
|
|
|
def cosine(x):
|
|
"""Return the cosine of x (in radians)."""
|
|
return math.cos(x)
|
|
|
|
def tangent(x):
|
|
"""Return the tangent of x (in radians)."""
|
|
return math.tan(x)
|
|
|
|
def logarithm(x, base=math.e):
|
|
"""Return the logarithm of x to the given base."""
|
|
if x <= 0:
|
|
raise ValueError("Logarithm undefined for non-positive values.")
|
|
return math.log(x, base)
|
|
|
|
def exponent(x, y):
|
|
"""Return x raised to the power y."""
|
|
return math.pow(x, y)
|
|
|
|
def main():
|
|
print("Scientific Calculator")
|
|
print("Select operation:")
|
|
print("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Sine\n6. Cosine\n7. Tangent\n8. Logarithm\n9. Exponent\n0. Exit")
|
|
while True:
|
|
choice = input("Enter choice: ")
|
|
try:
|
|
if choice == '1':
|
|
x, y = float(input("x: ")), float(input("y: "))
|
|
print("Result:", add(x, y))
|
|
elif choice == '2':
|
|
x, y = float(input("x: ")), float(input("y: "))
|
|
print("Result:", subtract(x, y))
|
|
elif choice == '3':
|
|
x, y = float(input("x: ")), float(input("y: "))
|
|
print("Result:", multiply(x, y))
|
|
elif choice == '4':
|
|
x, y = float(input("x: ")), float(input("y: "))
|
|
print("Result:", divide(x, y))
|
|
elif choice == '5':
|
|
x = float(input("x (radians): "))
|
|
print("Result:", sine(x))
|
|
elif choice == '6':
|
|
x = float(input("x (radians): "))
|
|
print("Result:", cosine(x))
|
|
elif choice == '7':
|
|
x = float(input("x (radians): "))
|
|
print("Result:", tangent(x))
|
|
elif choice == '8':
|
|
x = float(input("x: "))
|
|
base = input("Base (default e): ")
|
|
base = float(base) if base else math.e
|
|
print("Result:", logarithm(x, base))
|
|
elif choice == '9':
|
|
x, y = float(input("x: ")), float(input("y: "))
|
|
print("Result:", exponent(x, y))
|
|
elif choice == '0':
|
|
print("Goodbye!")
|
|
break
|
|
else:
|
|
print("Invalid choice.")
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|