Python Forum

Full Version: print either int or float - How?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello

I want to print number as whole if there is no decimal point and if there is decimal point, then print with decimal point.

For example,

length = float(input("Enter length: "))
width = float(input("Enter width: "))
total = length * width
print(f"The area of {length}x{width} is {total}")
The o/p be like

Output:
Enter length: 30 Enter width: 50 The area of 30.0x50.0 is 1500.0
OR

Output:
Enter length: 25 Enter width: 35.5 The area of 25.0x35.5 is 887.5
I want the output to be in whole number if there are no decimal points and in float if there are decimal points, like the following
Output:
The area of 30x50 is 1500 The area of 25x35.5 is 887.5
How do I format my print statement? Is that even possible?

Thanks
There are several approaches:
e.g. you can test the variable for it's "type".
a = 3.5
b = 5
if type(a) == float:
    print(a)
if type(b) == int:
    print(b)
or you could do
if int(b) == b:
    print(int(b))
Paul