How to find the smallest number in Python

In this post, we will learn how to find the smallest number.

The first program uses the if statement to achieve that.

The second program, the recommended way, uses the built-in min function and a list.

Code using the if statement

first_number = 32
second_number = 64
third_number = 128

if (first_number <= second_number) and (first_number <= third_number): 
    smallest_number = first_number
elif (second_number <= first_number) and (second_number <= third_number): 
    smallest_number = second_number
else:
    smallest_number = third_number

print(smallest_number)
#output: 32

The code snippet above uses the if statement to test the numbers and check which is the smallest one.

Three variables are declared with a number assigned to each one.

The if statement checks if the first_number is less than or equal to the second_number and the third_number.

The elif checks if the second_number is less than or equal to the first_number and the third_number.

Finally, if none of the prior conditions were met, logically, the third_number is the smallest one.

The program then prints the smallest_number variable with the answer.

But there is a problem with this approach.

What if you want to test more than three numbers?

You have to write an endless amount of if\’s and your code is gonna be messy and most probably buggy.

Check the next example to solve this.

Code using the built-in function min

first_number = 32
second_number = 64
third_number = 128

numbers = [first_number, second_number, third_number]

print(min(numbers))
#output: 32

The program above solves the problem of using multiple if‘s.

It takes the three numbers and puts them in a list.

Then the min built-in function is used to find the smallest among those numbers.

Using this approach you can have as many numbers as you want without having to add any extra logic.

If you want to know more about the if statement, check out this post Conditionals in Python.

I also recommend reading the opposite of this post How to find the largest number in Python.