Python Program to Find Maximum of Two Numbers


Approach 1 – Using Simple if else

In [1]:
a = float(input("Please enter value of a :"))
b = float(input("Please enter value of b :"))

#using simple if else
if a > b:
    print("Maximum number is:",a)
else:
    print("Maximum number is:",b)
Please enter value of a :20
Please enter value of b :12
Maximum number is: 20.0

In this program, we directly compare the two numbers using an if-else statement.

After prompting the user to enter two numbers using the input() function, we compare variable a and b to find the maximum. If ‘a’ is greater than ‘b’, we print “Maximum number is:” a else we print b.

Approach 2 – Using the Function

In [1]:
def find_max(a, b):
    if (a > b):
        return a
    else:
        return b
    
a = float(input("Please enter value of a :"))
b = float(input("Please enter value of b :"))

print("Maximum number is:",find_max(a, b))
Please enter value of a :26
Please enter value of b :33
Maximum number is: 33.0

In this program, we define a function called “find_max” that takes two numbers as input (a and b). It compares the two numbers using an if-else statement and returns the larger number.

Then, we prompt the user to enter two numbers using the input() function and store them in a and b variables. Finally, we call the find_max function with the entered numbers in the print statement and print the result, which is the maximum of the two numbers.

Note that the program assumes the user will enter valid numerical inputs.

Approach 3 – Using the max() Function

In [1]:
a = float(input("Please enter value of a :"))
b = float(input("Please enter value of b :"))

print("Maximum number is:",max(a, b))
Please enter value of a :78
Please enter value of b :45
Maximum number is: 78.0

In this program, we use the max() function to find the maximum of a and b. The max() function takes multiple arguments and returns the largest. We pass a and b as arguments to max().

We are calling the max function in the print statement itself.