How to find the maximum of three numbers in Python
How to find the maximum of three numbers in Python.
Here's a step-by-step tutorial on how to find the maximum of three numbers in Python. I'll provide multiple code examples where applicable.
Step 1: Define the three numbers
- Start by defining three variables to hold the three numbers you want to compare. For example, let's call them
num1
,num2
, andnum3
.
Step 2: Using the max()
function
- Python provides a built-in
max()
function that can be used to find the maximum value among multiple numbers. To use it, you can simply pass the three numbers as arguments to the function, like this:
maximum = max(num1, num2, num3)
The max()
function will return the highest value among the three numbers and store it in the variable maximum
.
Step 3: Using conditional statements
- If you prefer to avoid using the
max()
function, you can also use conditional statements to compare the numbers and find the maximum. Here's an example:
maximum = num1
if num2 > maximum:
maximum = num2
if num3 > maximum:
maximum = num3
In this example, we start by assuming that num1
is the maximum. Then, we compare num2
and num3
with the assumed maximum and update the maximum
variable accordingly.
Step 4: Printing the result
- Finally, you can print the maximum value to the console using the
print()
function. Here's an example:
print("The maximum number is:", maximum)
This will display the maximum value to the user.
Here's a complete example that combines all the steps:
num1 = 5
num2 = 10
num3 = 7
maximum = max(num1, num2, num3)
print("The maximum number is:", maximum)
Running this code will output: The maximum number is: 10
.
Alternatively, you can use the conditional statements approach:
num1 = 5
num2 = 10
num3 = 7
maximum = num1
if num2 > maximum:
maximum = num2
if num3 > maximum:
maximum = num3
print("The maximum number is:", maximum)
This will produce the same output: The maximum number is: 10
.
Feel free to adjust the numbers as per your requirement.