Skip to content
Advertisement

How do I get the user to input an int rather than a float?

I’m writing a program that takes in a value from the user, in the console, and I’m casting it to an int like so:

num = int(input("Enter a number: "))

I need my program to work with ints only. This works to convert an actual int entered into the console to an int I can use in the program, but if the user enters a float, like 3.1, then it doesn’t cast to an int by truncating or rounding up for example.

How do I get the user to input an int rather than a float? Or how do I convert a floating point input to an int?

Advertisement

Answer

You can use a try catch block to ensure they only give you an int:

while True:
    try:
        num = int(input("Enter a number: "))
        #do something with num and then break out of the while loop with break
    except ValueError:
        print("That was not a number, please do not use decimals!")

When ValueError (when it fails to convert to int) is excepted it goes back to asking for a number which once you get your number you can do things with said number or break out of the loop then and use num elsewhere.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement