Advertisement
SkidScripts

Complex Calculator (Python)

Nov 29th, 2023
1,304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. import math
  2.  
  3. def add(x, y):
  4.     return x + y
  5.  
  6. def subtract(x, y):
  7.     return x - y
  8.  
  9. def multiply(x, y):
  10.     return x * y
  11.  
  12. def divide(x, y):
  13.     if y == 0:
  14.         return "Cannot divide by zero!"
  15.     else:
  16.         return x / y
  17.  
  18. def power(x, y):
  19.     return x ** y
  20.  
  21. def sqrt(x):
  22.     if x < 0:
  23.         return "Invalid input for square root of a negative number!"
  24.     else:
  25.         return math.sqrt(x)
  26.  
  27. def logarithm(x, base):
  28.     if x <= 0 or base <= 0 or base == 1:
  29.         return "Invalid input for logarithm!"
  30.     else:
  31.         return math.log(x, base)
  32.  
  33. print("Select operation:")
  34. print("1. Addition")
  35. print("2. Subtraction")
  36. print("3. Multiplication")
  37. print("4. Division")
  38. print("5. Exponentiation")
  39. print("6. Square Root")
  40. print("7. Logarithm")
  41.  
  42. while True:
  43.     choice = input("Enter choice (1/2/3/4/5/6/7): ")
  44.  
  45.     if choice in ('1', '2', '3', '4', '5', '6', '7'):
  46.         if choice in ('1', '2', '3', '4', '5'):
  47.             num1 = float(input("Enter first number: "))
  48.             num2 = float(input("Enter second number: "))
  49.  
  50.             if choice == '1':
  51.                 print("Result:", add(num1, num2))
  52.             elif choice == '2':
  53.                 print("Result:", subtract(num1, num2))
  54.             elif choice == '3':
  55.                 print("Result:", multiply(num1, num2))
  56.             elif choice == '4':
  57.                 print("Result:", divide(num1, num2))
  58.             elif choice == '5':
  59.                 print("Result:", power(num1, num2))
  60.         elif choice == '6':
  61.             num = float(input("Enter a number: "))
  62.             print("Result:", sqrt(num))
  63.         elif choice == '7':
  64.             num = float(input("Enter a number: "))
  65.             base = float(input("Enter the base for logarithm: "))
  66.             print("Result:", logarithm(num, base))
  67.        
  68.         break
  69.     else:
  70.         print("Invalid input. Please enter a valid number (1/2/3/4/5/6/7).")
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement