Python Program to Find the Maximum of Two Numbers.

Given two numbers num1 and num2, write a Python program to find the maximum of two numbers.

Example:
Input: num1 = 10, num2 = 15
Output: 15

Input: num1 = -5, num2 = -2
Output: -2

Approach 1: Comparing two numbers using the if..else statement.

Explanation:
  • In the first two lines, the program takes input for two numbers.
  • In the next few lines, the program uses an if statement to compare the two numbers and find the maximum.
  • Finally, the program prints the result.
Python Example Code:
# take input for the two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# compare the two numbers and find the maximum
if num1 > num2:
    maximum = num1
else:
    maximum = num2

# print the result
print("The maximum number is", maximum)
Output:
Enter first number: 10
Enter second number: 15
The maximum number is 15
  • Time Complexity: O(1)
  • Space Complexity: O(1)

Approach 2: Using the max() function. This function returns the maximum of the values passed as its arguments.

Explanation:
  • The first two lines are the same, taking input for the two numbers.
  • In the next line, the program uses the max() function to find the maximum of the two numbers.
  • Finally, the program prints the result.
Python Example Code:
# take input for the two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# use the max function to find the maximum of the two numbers
maximum = max(num1, num2)

# print the result
print("The maximum number is", maximum)
Output:
Enter first number: -10
Enter second number: -15
The maximum number is 10
  • Time Complexity: O(1)
  • Space Complexity: O(1)

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS