In this article, We will see different ways to write a Python code to find the maximum of two numbers.
Examples:
Input: number1 = 10, number2 = 5 Output: 10 Input: number1 = 25, number2 = 50 Output: 50
Now, let’s see the different ways to code this program:
Code 1: By using Comparison Operator.
# given input number1 = 10 number2 = 5 # check for greater value if number1 > number2 : print("Maximum:", number1) else: print("Maximum:", number2)
Output:
Maximum: 10
Code 2: By using max() built-in function.
# given input number1 = 20 number2 = 25 # max() built-in function call # for finding maximum # of two numbers print("Maximum:", max(number1,number2))
Output:
Maximum: 25
Code 3: By creating user-defined function.
# Create a user defined function # for finding maximum of two # numbers def maximum(number1, number2) : # return maximum value return max(number1, number2) # main code if __name__ == "__main__" : # taking input from user and # convert it into int data type number1 = int(input("Enter 1st Number:")) number2 = int(input("Enter 2nd Number:")) # function calling and printing print("Maximum:", maximum(number1, number2))
Output:
Enter 1st Number:45 Enter 2nd Number:65 Maximum: 65
Code 4: By Creating anonymous : one- line function.
# Create a anonymous/lambda function # for finding maximum of two # numbers maximum = lambda number1, number2 : number1 if number1 > number2 else number2 # main code if __name__ == "__main__" : # given input number1 = 25 number2 = 50 print("Maximum:", maximum(number1 , number2))
Output:
Maximum: 50