Advertisement
Fleshian

Untitled

Aug 21st, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1.  
  2. def get_sum(num1, num2):
  3.     return num1 + num2
  4.  
  5.  
  6. def subtract(num1, num2):
  7.     return num1 - num2
  8.  
  9.  
  10. def divide(num1, num2):
  11.     return num1 / num2
  12.  
  13.  
  14. def multiply(num1, num2):
  15.     return num1 * num2
  16.  
  17.  
  18. def get_operation():
  19.     operator_input = raw_input("Please enter a valid sign (+,-,/-*): ")
  20.     switcher = {
  21.         "+": get_sum,
  22.         "-": subtract,
  23.         "/": divide,
  24.         "*": multiply
  25.     }
  26.     # operation func returns the appropriate function or "Invalid sign" string.
  27.     operation_func = switcher.get(operator_input, "Invalid sign")
  28.     if operation_func == "Invalid sign":
  29.         return get_operation()  # This is recursion meaning invoking a function from itself
  30.     return operation_func
  31.  
  32.  
  33. def get_num(input_message):
  34.     try:
  35.         num = float(raw_input(input_message))
  36.     except ValueError:
  37.         return get_num("Please Enter a valid number: ")
  38.     return num
  39.  
  40.  
  41. def calculate(operation, num1, num2):
  42.     res = operation(num1, num2)
  43.     # Checks if the calculated answer is an integer so it doesn't print with .0 at the end.
  44.     if res % 1 == 0:
  45.         return int(res)
  46.     return float(res)
  47.  
  48.  
  49. first_num = get_num("Please enter the first number: ")
  50. second_num = get_num("Please enter the second number: ")
  51. result = calculate(get_operation(), first_num, second_num)
  52. print(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement