1

How do I output the result of an expression where if the user enters a float number and an integer, the result will include decimal, and if the user gives both number in an integer form, the result will not include decimal.

Example:

num_1 = float(input("\nEnter first number: "))

opr = input("Enter math operator: ")

num_2 = float(input("Enter second number: "))

if opr == "+":
    print(num_1 + num_2)
elif opr == "-":
    print(num_1 - num_2)
else:
    print("Invalid math operator")

>>> Enter first number: 2.5
>>> Enter math operator: +
>>> Enter second number: 3

5.5

The code above works for a float number that's because the input has been converted to float to avoid ValueError. But the result will always be a float number. How can I make 2 + 2 = 4 and not 4.0?

CoreVisional
  • 99
  • 1
  • 6

1 Answers1

1

Solution 1

A simple and straightforward solution is to convert it into an int and check if it's value is same as it's float counter-part.

For example, if float_output=4.0, it's int_output would be set to 4. And the logic of 4 == 4.0 would end in True. Therefore, the int_output is set as the final_output in this case.

Else, consider that float_output=4.5, it's int_output would be set to 4. And the logic of 4 == 4.5 would end in False. Therefore, the float_output is set as the final_output.

Here is the complete code:

num_1 = float(input("Enter first number: "))

opr = input("Enter math operator: ")

num_2 = float(input("Enter second number: "))

float_output = None

if opr == "+":
    float_output = num_1 + num_2
elif opr == "-":
    float_output = num_1 - num_2
else:
    print("Invalid math operator")

if float_output is not None:
    int_output = int(float_output)
    if int_output == float_output:
        final_output = int_output
    else:
        final_output = float_output
    print(final_output)

Solution 2

You can use the float.is_integer() which is an inbuilt function for floats to do this check automatically.

This is how you would do it in that case:

num_1 = float(input("Enter first number: "))

opr = input("Enter math operator: ")

num_2 = float(input("Enter second number: "))

float_output = None

if opr == "+":
    float_output = num_1 + num_2
elif opr == "-":
    float_output = num_1 - num_2
else:
    print("Invalid math operator")

if float_output.is_integer():
    print(int(float_output))
else:
    print(float_output)
S P Sharan
  • 1,101
  • 9
  • 18
  • what if I want to display the number input by the user? Should something like this `print(f"{int(num_1)} + {int(num_2)} = ", int(result))` be suitable? For example, I want to display `2 + 2 = 4`, but `num_1` and `num_2` still display 2.0 instead of 2. Also, is `float_output = None` a must? I removed it and the result is still the same. – CoreVisional Aug 18 '21 at 06:10