Python maximum

In this lesson we will write a Python program to find the maximum between two numbers, in order to put into practice what we have studied so far.

Python Program on the maximum of two numbers

Given two integers a and b, find the maximum value in Python. If the numbers are the same, also display the message: ‘the numbers are the same‘.

In particular, I propose a couple of solutions. In the first I use elif, while in the second I use nested if statement.

First solution with the use of elif

I present a very simple first solution with the use of the elif instruction to find the maximum of 2 numbers in Python:


a = int(input('Insert the first number:'))
b = int(input('Insert second number:'))

if a > b:
    print('The largest value is a:', a)
elif a == b:
    print('The numbers are the same')
else:
    print('The largest value is b:', b)

Second solution with the use of nested if statement

I present a second solution, which is also very simple, with the use of the nested if statement to find the maximum of 2 numbers in Python:


a = int(input('Insert the first number:'))
b = int(input('Insert second number:'))

if a > b:
    print('The largest value is a:', a)
else:
   if a == b:
      print('The numbers are the same')
   else:
      print('The largest value is b:', b)

Furthermore, thanks to multiple assignment, a topic I covered in the lesson on the exchange of values, the input values ​​a and b can also be taken in this way:

a, b = int(input (‘Insert the first number:’)), int(input (‘Insert the second number:’))

This is just an example of a possible resolution of the algorithm for calculating the maximum between two numbers in Python, propose yours in the comments below.

Conclusion

In this lesson we have seen a simple algorithm to find the maximum between two numbers, in the next lessons we will see how to find the maximum between N numbers.

Useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *