Maximum of Two Numbers in Python

1. Introduction

In Python, determining the maximum of two numbers is a basic operation that can be implemented in various ways. This blog post will guide you through creating a simple Python program to find the maximum of two user-provided numbers. Understanding how to compare numbers and execute conditional logic is foundational in programming, and this example will help solidify these concepts.

2. Program Steps

1. Prompt the user to input two numbers.

2. Convert the input values to the appropriate numerical type (e.g., integers or floating-point numbers) for comparison.

3. Compare the two numbers using a conditional statement to determine which one is greater.

4. Display the maximum number to the user.

3. Code Program

# Step 1: Prompt the user for two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Step 2: Compare the numbers and find the maximum
if num1 > num2:
    max_num = num1
else:
    max_num = num2

# Step 3: Display the maximum number
print("The maximum number is:", max_num)

Output:

Enter the first number: 45
Enter the second number: 32
The maximum number is: 45

Explanation:

1. The program starts by asking the user to enter two numbers. These are read as strings from the standard input using the input function and then converted to floating-point numbers (to accommodate decimal values) using the float function.

2. It then compares the two numbers using an if-else statement. If num1 is greater than num2, num1 is assigned to max_num. Otherwise, num2 is assigned to max_num.

3. Finally, the program prints out the maximum number using the print function. The output shows which of the two input numbers is greater.


Comments