Kodeclik Blog


math.floor() in Python

Let us suppose you have 18 dollars to spend at the county fair. You would like to take a ride on the ferris wheel which costs 5 dollars. How many rides can you take? Let us write a simple Python program for this problem:
The output will be:
meaning you can take 3.6 rides. But there is no such thing as a fractional ride! What you can surmise from this is that you can take 3 rides and will have some money left over.
To accomplish this in Python, you can use the handy math.floor() function. It takes a number as input and rounds it down to the nearest integer. Here is how that works.
Note that we first import the math package so we can then use the floor function provided with it. The output will be:
indicating that you can take 3 rides.

math.floor() with negative numbers

Let us try math.floor() with negative numbers like so:
we will get:
Recall that we always round down to the next lowest integer. So the next lowest integer to -1.4 is -2. To confirm, let us try:
Now -1.1 is really close to -1, i.e., closer to -1 than to -2. But the output of the above program will still be:
because math.floor() always rounds down (see figure above). The formal way of saying this is that math.floor() always returns the largest integer value less than or equal to the input provided.
To summarize, the floor function in Python is a mathematical function that returns the largest integer less than or equal to a given number. The floor function is often used in conjunction with the ceil function, which returns the smallest integer greater than or equal to a given number. Also checkout the related math.isclose() function in Python.
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.