I am a very new programmer. I have created this calculator in python, and I wanted to polish it up a bit. Whenever I make a calculation, the answer is always printed as a float, even when both inputs were just integers. (for example: 5 + 5 = 10.0) I know this is because I convert the inputs to floats immediately, but I am entirely lost on how I can make the answer appear as a float only when one of the inputs contains a decimal. Thank you for any help in advance.
Here is my code (I know it is a bit messy, my bad, I am quite new):
while True: try: calculating = input('would you like to make a calculation? (y/n) ')
if calculating in ('y', 'yes'):
try:
numberOne = float(input('Enter your first number. '))
operation = input('Enter your operator. ')
if operation not in ('+', '-', '*', 'x', '/'):
print('That is not an operator.')
continue
numberTwo = float(input('Enter your second number. '))
except ValueError as e:
print(e)
continue
if operation == '+':
print(float(numberOne) + float(numberTwo))
if operation == '-':
print(float(numberOne) - float(numberTwo))
if operation in ('*', 'x'):
print(float(numberOne) * float(numberTwo))
try:
if operation == '/':
print(float(numberOne) / float(numberTwo))
except ZeroDivisionError:
print('Error: Division by 0')
continue
elif calculating in ('n', 'no'):
print('Okay')
break
if calculating not in ('y', 'n', 'yes', 'no'):
print('It is one or the other')
continue
except Exception as e:
print(e)
I tried having two seperate blocks where the inputs are actually calculated, each with an "if numberOne == float/int or numberTwo == float/int" statement before. I realized this wasn't working because I was saving each input as a float as soon as it was entered because of the float() function around the input(). However, if I were to remove that it would be stored as a string and then I wouldn't know how to convert it to either a float or an integer based on whether or not it contained a decimal. I am sure there is a simple fix to this problem, but I am just not seeing it. Thank you in advance.
Check if a decimal point is present in the string input, before converting to int/float.
number = input("Enter a number ")
if "." in number:
number = float(number)
else:
number = int(number)