acclivity

pyTextBasedCalculator

May 18th, 2022 (edited)
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.23 KB | None | 0 0
  1. # A simple text based calculator project in Python
  2. # This is a common student task
  3.  
  4. def get_float(prompt):
  5.     while True:
  6.         s = input(prompt)
  7.         try:
  8.             return s, float(s)      # here I return the original string AND the float value
  9.         except:
  10.             print("Invalid input\n")
  11.             # here the code loops back to request input again
  12.  
  13.  
  14. while True:
  15.     print("A: Add\nS: Subtract\nM: Multiply\nD: Divide \nP: Power \nR: Remainder\nQ: Quit")
  16.     while True:
  17.         op = input("Select an operation: ")
  18.         op = op.upper()[0]
  19.         if op in ['A', 'S', 'M', 'D', 'P', 'R', 'Q']:
  20.             break
  21.         print("Operation not recognised\n")
  22.  
  23.     if op == "Q":
  24.         break
  25.  
  26.     usera, a = get_float("Enter first number: ")
  27.     userb, b = get_float("Enter second number: ")
  28.     # Find out if both user inputs were integers
  29.     both_int = a == int(a) and b == int(b)
  30.     if op in "DR" and b == 0.0:         # b must not be zero for division or remainder operations
  31.         print("******* Divide by zero error *******\n")
  32.         continue
  33.  
  34.     if op == "A":
  35.         # Show the original user input strings, to avoid confusion between floats and integers
  36.         if both_int:
  37.             print(f"{usera} plus {userb} equals {int(a + b)}")
  38.         else:
  39.             print(f"{usera} plus {userb} equals {a + b:.02f}")
  40.     elif op == "S":
  41.         if both_int:
  42.             print(f"{usera} minus {userb} equals {int(a - b)}")
  43.         else:
  44.             print(f"{usera} minus {userb} equals {a - b:.02f}")
  45.     elif op == "M":
  46.         if both_int:
  47.             print(f"{usera} times {userb} equals {int(a * b)}")
  48.         else:
  49.             print(f"{usera} times {userb} equals {a * b:.02f}")
  50.     elif op == "D":
  51.         print(f"{usera} divided by {userb} equals {a / b:.02f}")
  52.     elif op == "P":
  53.         print(f"{usera} to the power of {userb} equals {a ** b:.02f}")
  54.     elif op == "R":
  55.         # Remainder operation requires integers only
  56.         if int(a) != a or int(b) != b:
  57.             print("Integers only for this operation")
  58.         else:
  59.             print(f"{usera} divided by {userb} gives a remainder of {int(a) % int(b)}")
  60.     input("\nPress enter to continue ")
  61.  
  62. print("Goodbye")
  63.  
  64.  
Add Comment
Please, Sign In to add comment