In this post, we will learn how to find the largest number.
The first program uses the if
statement to achieve that.
The second program, the recommended way, uses the built-in max
function and a list
.
Code using the if
statement
first_number = 32
second_number = 128
third_number = 64
if (first_number >= second_number) and (first_number >= third_number):
largest_number = first_number
elif (second_number >= first_number) and (second_number >= third_number):
largest_number = second_number
else:
largest_number = third_number
print(largest_number)
#output: 128
The code snippet above uses the if
statement to test the numbers and check which is the largest one.
Three variables are declared with a number assigned to each one.
The if
statement checks if the first_number
is greater than or equal to the second_number
and the third_number
.
The elif
checks if the second_number
is greater 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 largest one.
The program then prints the largest_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 max
first_number = 32
second_number = 64
third_number = 128
numbers = [first_number, second_number, third_number]
print(max(numbers))
#output: 128
The program above solves the problem of using multiple if
‘s.
It takes the three numbers and puts them in a list
.
Then the max
built-in function is used to find the largest 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 smallest number in Python.