Python Float – Numbers With Decimals, Examples

Python float refers to a data type. A data type is a fancy word for data format, similar to having different formats in excel. Floats specifically refer to numbers with a decimal point.

x = 5.6 # Floats are numbers with decimal points
print (type(x))
>>> <class 'float'>

In this case, round numbers (Ex: 5.0), can be floats too, all that matters is they have a decimal point. As you’re working with data, differentiating floats vs int (no decimal points) isn’t a problem…until it is.

Usually you won’t think about specifying floats or ints, but every now and then you’ll get an error that says “can not recognize float.” You’ll know that this is a data type problem you’ll need to fix.

Python Float Error: “invalid literal for int() with base 10:”

This is a common error you’ll see when trying to convert a string that looks like a float (Ex: ‘9.34’) into an int directly. You’ll need to first convert this to a float (and not a string), then to an int. Like this: int(float(‘9.34’)

Let’s take a look at a python float code sample

Python Float

In Python, there are many different types of data. Think of these as different formats in Excel. The one we're looking at today, is float.

The easiest way to remember these are numbers with decimal places. Let's take a look at a few

In [5]:
x = 5.6
y = 7

print ("x is: {}".format(x))
print ("x is type: {} \n".format(type(x)))

print ("y is: {}".format(y))
print ("y is type: {}".format(type(y)))
x is: 5.6
x is type: <class 'float'> 

y is: 7
y is type: <class 'int'>

It's not the fact that x is not a round number. It's the fact that it has a decimal place at all.

In [7]:
i = 5
f = 5.0

print ("i is: {}".format(i))
print ("i is type: {} \n".format(type(i)))

print ("f is: {}".format(f))
print ("f is type: {}".format(type(f)))
i is: 5
i is type: <class 'int'> 

f is: 5.0
f is type: <class 'float'>

Link to code above

Check out more Python Vocabulary on our Glossary Page