A “literal” value is one that is typed into code. Think “4.1”, a floating point literal value, or “asdf”, a literarl string value. You can learn a lot about data types by typing them into Python to learn how they work. The type()
function returns the data type of the input object.
Let’s use type()
to learn about Python’s built in data types. Two basic numeric types include floats and integers.
type(4.1)
float
type(4)
int
the int
and float
types returned are classes that can be used to cast variables. For example,
int(4.1)
4
can be used to convert a floating point literal, 4.1, to an integer, 4. It’s returned type is an int
type(int(4.1))
int
conversely, you can convert an int back into a float, using
float(int(4.1))
4.0
and the returned type is
type(float((int(4.1))))
float
You can also define numbers using different notations, inculding hexadecimal,
0xff
255
or binary
0b00111010
58
Boolean Type
Another data type is the boolean data type or bool
. Boolean variables hold one of two values, either true or false.
True
True
type(True)
bool
False
False
Boolean values are returned when used with operations like equality or inequality tests.
1==2
False
3!=5
True
1>2
False
3<=4
True
Integer Math
when you operate on two integers, the result is returned as an integer as well.
1
1
1+2
3
2-1
1
a = 1
b = 2
a+b
3
Float Operations
Because integers exist within the set of all floating point numbers, operating on an int and a float will return a floating point number as well.
import math
1.1
1.1
1.1*2.2
2.4200000000000004
2*1.1
2.2
Some functions can be used to convert a floating point number back to an integer. The first is obviously the int class itself.
int(4.1)
4
The round()
function always rounds to the nearest integer. floats with a .5 are rounded up to the largest absolute value integer.
round(1.4)
1
round(1.5)
2
round(-1.4)
-1
round(-1.5)
-2
Other functions include trunc()
, which eliminates the mantissa, floor()
, which returns the smaller absolute-value integer, and ceil()
which returns the larger absolute-value integer.
math.trunc(1.8)
1
math.floor(1.8)
1
math.trunc(-1.8)
-1
math.floor(-1.8)
-2
math.ceil(1.8)
2
math.ceil(-1.8)
-1
Conversions
You can also use the data type class itself to convert from one data type to another
int(8.1)
8
float(8)
8.0
int(8)
8
str(9.815)
'9.815'
bool(8.15)
True
float(str(8.15))
8.15
int(str(8))
8
Some conversions cannot be made implicitly:
try:
int(str(8.15))
except ValueError as e:
print(e)
invalid literal for int() with base 10: '8.15'