Kodeclik Logo

Our Programs

Learn More

Schedule

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:

num_dollars = 18
ferris_cost = 5
print(num_dollars/ferris_cost)

The output will be:

3.6

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.

import math

num_dollars = 18
ferris_cost = 5
print(math.floor(num_dollars/ferris_cost))

Note that we first import the math package so we can then use the floor function provided with it. The output will be:

3

indicating that you can take 3 rides.

math.floor() with negative numbers

math.floor() in Python

Let us try math.floor() with negative numbers like so:

import math

print(math.floor(-1.4))

we will get:

-2

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:

import math

print(math.floor(-1.1))

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:

-2

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.

Kodeclik sidebar newsletter

Join our mailing list

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

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.