Published

2025-03-31

Open In Colab

Numeric Types (Int and Float) & Booleans

Justin Post


Next up, we look at two basic built-in data types: numeric types and booleans

As with lists and strings, we’ll go through and look at how to create them, common methods and functions, and look at some examples along the way.

Once we’re through this part, we’re ready to start thinking about compound data types (other than lists) and how we might store and summarize data. For dealing with data, we’ll look at two common python modules and their data types:

  • NumPy arrays
  • Pandas data frames

Note: These types of webpages are built from Jupyter notebooks (.ipynb files). You can access your own versions of them by clicking here. It is highly recommended that you go through and run the notebooks yourself, modifying and rerunning things where you’d like!


Ints & Floats

  • (Real) Numbers are stored as int or float types
    • Python generally figures out which to use and changes to float when needed
x = 10
type(x)
int
y = 10.4
type(y)
float
z = y - 0.4
print(z)
type(z)
10.0
float
type(x + 0.5)
float
  • You can cast things (or explicitly coerce them) using int() and float()
x = 10
print(type(x))
x
<class 'int'>
10
x = float(x)
print(type(x))
x
<class 'float'>
10.0
int(10.9) #returns just the integer part (no rounding done)
10

Functions & Operators

  • We have all the numeric operators discussed previously and a few handy functions built in too
#divide and discard remainder
100 // 3
33
#modulus or remainder
100 % 3
1
#whole number division and modulus
divmod(100, 3) #returns a 'tuple' (a sort of immutable list)
(33, 1)
#raise to a power 4^3
pow(4, 3)
64
#equivalent to
4 ** 3
64
abs(-100)
100
round(10.4242, 2)
10.42

math module

  • As we saw, the math module has a number of useful functions
  • Recall we can import the math module to gain access to its functions. We then preface functions/objects from the module with math.
x = 10.55
#a boolean function (more on this shortly)
x.is_integer()
False
import math
math.floor(x)
10
math.ceil(x)
11
math.factorial(10)
3628800

Things To Be Aware Of

Floats are not stored precisely!

1.2-1.0
0.19999999999999996
  • Comes from using a binary representation of floats

  • Not worth getting into, but if you see something weird like this, that is why!

  • More info here


Things to Note/Remember

  • Augmented assignment operators are useful
x = 100
x += 200
x
300
  • Multiple assignment can be done
x = y = z = 40
print(x, y)
40 40
x, y, z = 40, 50, 60
print(x, y)
print(z)
40 50
60

More Formatting Strings

We saw how to format strings earlier. Let’s revit that year!

Job = "Professor"
Years = 10.23
my_string = "I am a {job} and I've been teaching for {years:d} years"

We can use the .format() method on the string to place values in the placeholders. The years:d above specifies the type of formatting to use on the number, d stands for integer

my_string.format(job = Job, years = Years) #throws an error as it expects an integer for years
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-41-7105395599c7> in <cell line: 1>()
----> 1 my_string.format(job = Job, years = Years) #throws an error as it expects an integer for years

ValueError: Unknown format code 'd' for object of type 'float'
my_string.format(job = Job, years = int(Years)) #cast years as an integer via int()
"I am a Professor and I've been teaching for 10 years"

We can specify the type of number input for the .format() method to use via this name:number_type syntax:

  • d - Integers
  • f - Floating point numbers
  • .f - Floating point numbers with a fixed amount of digits to the right of the dot.
print("I am a {job} and I've been teaching for {years:f} years".format(job = Job, years = Years))
print("I am a {job} and I've been teaching for {years:.1f} years".format(job = Job, years = Years))
I am a Professor and I've been teaching for 10.230000 years
I am a Professor and I've been teaching for 10.2 years

Actually four different ways to substitute into a string (if you are interested!)


Booleans

  • A bool is a True or False value (note the case of these two special terms)
x = True
type(x)
bool

Many functions and methods return a boolean. For instance, the .is_integer() method:

y = 10.1
y.is_integer()
False

For strings (and other objects we’ll see) in and not in are useful operators that return a boolean

"an" in "banana"
True
"pa" not in "panama"
False

isInstance() is a useful function to determine if an object is a certain type!

isinstance(10.4, float)
True
  • Booleans are very useful for control flow operators like if/then/else and looping (covered soon!)
  • You can use the bool() function on anything to get a True or False
    • Any list, tuple, set, and dictionary are True except empty ones
bool("string")
True
bool("")
False
bool(10)
True
bool(0)
False
#None is keyword to define a null value in python
bool(None)
False
#not can be used to negate something and make it True
bool(not None)
True
bool(not 10)
False

Boolean/Integer Relationship

  • Booleans are actually a subtype of integers
    • True treated as 1
    • False treated as 0
print(3 + True, 3 * False)
4 0

One thing of note is that when you do math on True or False it converts the result. Note the last computation result below.

print(str(True), str(False), str(True + 0))
True False 1

Video Demo

This quick video shows some useful functions from the .math module for dealing with integers, floats, and booleans. Remember to pop the video out into the full player.

The notebook written in the video is available here.

from IPython.display import IFrame
IFrame(src="https://ncsu.hosted.panopto.com/Panopto/Pages/Embed.aspx?id=d59f4288-1a98-446e-a82f-b0f0013e8445&autoplay=false&offerviewer=true&showtitle=true&showbrand=true&captions=false&interactivity=all", height="405", width="720")

Recap

  • Numbers stored as ints or floats

    • standard operations all available
    • math module has more functionality
  • Booleans are True or False

    • Can be treated as 1 and 0
    • Many functions to create bools (.is_*() methods, bool() function)

If you are on the course website, use the table of contents on the left or the arrows at the bottom of this page to navigate to the next learning material!

If you are on Google Colab, head back to our course website for our next lesson!