Take a Float or Integer Input in Python

When you learn Python, one of the first operation you are asked to perform is to ask an input from the user, using the input() fonction. This function only takes one argument, which is the message displayed to the user, and it returns a string. Now, how can we convert this string to a number (integer or float)? In this tutorial, we’ll see how we can simply achieve that.

What input() returns

By default ans as we explained in the introduction, the input() function always returns a string. We can check it running the type() function on the returned value, even if it is a number.

age = input('What is your age?') print(type(age))
Code language: Python (python)

output:

<class 'str'>
Code language: Python (python)

There is no way to force Python to accept only numbers for an input() function; therefore we must take care of the transformation ourselves.

Convert an input to float

To take a float input means basically to convert the string returned by the input() function to a float. We can do that using the float() function.

age = float(input('What is your age?')) print(type(age))
Code language: PHP (php)

Output:

<class 'float'>
Code language: Python (python)

Now the code will work only if the user inputs an integer or a float. What happens if it inputs a text, for instance. Well, Python will raise an error:

Traceback (most recent call last): File "<string>", line 1, in <module> ValueError: could not convert string to float: 'text'
Code language: Python (python)

To avoid it, I advise using a more complex code, but that will handle these cases that will tell the user that they need to input a number.

age = input('What is your age?') try: #we try to convert the input to float age = float(age) #if we can't except: raise ValueError('You must enter a number!!')
Code language: Python (python)

Convert an input to integer

You can follow the same logic, but using the int() and not the float() function.

age = int(input('What is your age?')) print(type(age))
Code language: PHP (php)

Output:

<class 'int'>
Code language: HTML, XML (xml)

Leave a Reply

Your email address will not be published. Required fields are marked *