Search code examples
pythoninteger

Why doesn't the int() function convert a float to integer while in input() function?


Why doesn't the int() function convert a float to integer while in input() function?

input_1 = input(f'enter the num: ')

try: 
    a = int(input_1)
    print(f"it is an integer")
except:
    print(f"no an integer")
    

input_1 = 3.532453

try: 
    a = int(input_1)
    print(f"it is an integer")
except:
    print(f"no an integer")

Result:

enter the num: 3.532453
no an integer
it is an integer

Solution

  • So you can change a decimal to an int in python. But not without losing all the data past the decimal point. For example if you convert "12.3356" to an int using int(float("12.3356") and the result would be 12.

    An int value in python is one without a decimal point for eg: 3.

    A float value in python is a number with a decimal point for eg: 3.141.

    So, if you want to check if what a user enters is a number and conserve everything past the decimal point, convert the strings to a float instead of an int:

    input_1 = input('enter the num: ')
    
    try:
        a = float(input_1)
        print("it is a number")
    except ValueError:
        print("not a number")
    

    By using float() instead of int(), you get to keep all the data past the decimal point (if you need it in other parts of your program).

    However, if you still want to convert a float to an int (and lose everything past the decimal point), you can do:

    Note that the below is basically extra code for a disadvantage and the above is usually better (in most cases), but if that's what you want well here you go:

    input_1 = input('enter the num: ')
    
    try:
        a = int(float(input_1))
        print("it is a number")
    except ValueError:
        print("not a number")