Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # A simple text based calculator project in Python
- # This is a common student task
- def get_float(prompt):
- while True:
- s = input(prompt)
- try:
- return s, float(s) # here I return the original string AND the float value
- except:
- print("Invalid input\n")
- # here the code loops back to request input again
- while True:
- print("A: Add\nS: Subtract\nM: Multiply\nD: Divide \nP: Power \nR: Remainder\nQ: Quit")
- while True:
- op = input("Select an operation: ")
- op = op.upper()[0]
- if op in ['A', 'S', 'M', 'D', 'P', 'R', 'Q']:
- break
- print("Operation not recognised\n")
- if op == "Q":
- break
- usera, a = get_float("Enter first number: ")
- userb, b = get_float("Enter second number: ")
- # Find out if both user inputs were integers
- both_int = a == int(a) and b == int(b)
- if op in "DR" and b == 0.0: # b must not be zero for division or remainder operations
- print("******* Divide by zero error *******\n")
- continue
- if op == "A":
- # Show the original user input strings, to avoid confusion between floats and integers
- if both_int:
- print(f"{usera} plus {userb} equals {int(a + b)}")
- else:
- print(f"{usera} plus {userb} equals {a + b:.02f}")
- elif op == "S":
- if both_int:
- print(f"{usera} minus {userb} equals {int(a - b)}")
- else:
- print(f"{usera} minus {userb} equals {a - b:.02f}")
- elif op == "M":
- if both_int:
- print(f"{usera} times {userb} equals {int(a * b)}")
- else:
- print(f"{usera} times {userb} equals {a * b:.02f}")
- elif op == "D":
- print(f"{usera} divided by {userb} equals {a / b:.02f}")
- elif op == "P":
- print(f"{usera} to the power of {userb} equals {a ** b:.02f}")
- elif op == "R":
- # Remainder operation requires integers only
- if int(a) != a or int(b) != b:
- print("Integers only for this operation")
- else:
- print(f"{usera} divided by {userb} gives a remainder of {int(a) % int(b)}")
- input("\nPress enter to continue ")
- print("Goodbye")
Add Comment
Please, Sign In to add comment