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:
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:
- We use the
input
function to get two numbers from the user, and we convert them to floating-point numbers usingfloat()
since we want to handle decimal values as well. - We compare the two numbers using an
if
statement. Ifnum1
is greater thannum2
, we setlargest
tonum1
, otherwise, we set it tonum2
. - 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.