Skip to content

Python program to find largest of 2 numbers | Example code

  • by

To write a program to find the largest of 2 numbers use the if-else statement in Python, You have to compare two numbers using the if-else statement and will print the largest number.

Python program to find the largest of 2 numbers example

A simple example code prints the greatest of two numbers using an if-else statement.

def maximum(a, b):
    if a >= b:
        return a
    else:
        return b


# Driver code
a = 0
b = 7
print("Largest number", maximum(a, b))

Output:

Python program to find largest of 2 numbers

Using user input

# Input two numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Compare the two numbers and find the largest
if num1 > num2:
    largest = num1
else:
    largest = num2

# Print the largest number
print("The largest number is:", largest)

In this program:

  1. We use the input function to get two numbers from the user, and we convert them to floating-point numbers using float() since we want to handle decimal values as well.
  2. We compare the two numbers using an if statement. If num1 is greater than num2, we set largest to num1, otherwise, we set it to num2.
  3. Finally, we print out the largest number using the print function.

You can run this program, and it will tell you which of the two numbers is the largest.

Do comment if you have any doubts or suggestions on this Python program.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *