Hey I recently started to learn python. Below is the program to find the largest number, I want to know how do I print the second largest number. Thanks in advance.
x=int(input("Enter the 1st number: \n"))
y=int(input("Enter the 2nd number: \n"))
z=int(input("Enter the 3rd number: \n"))
if x>y:
f1=x
else:
f1=y
if y>z:
f2=y
else:
f2=z
if f1>f2:
print(str(f1)+" is greatest")
else:
print(str(f2)+" is greatest")
You can easily get the second largest number by adding the input to a list and sorting it.
Try this:
xyz = [x,y,z]
sorted_xyz = sorted(xyz)
largest = sorted_xyz[-1]
second_largest = sorted_xyz[-2]
Since you want this to work with conditional statements. You can try:
# check if x is the largest
if ( x >= y and x >= z ):
print(str(x) + " is the greatest")
# check if y is greater than z, if so then it is the second largest number.
if ( y >= z ):
print(str(y) + " is second greatest")
else:
print(str(z) + " is second greatest")
# check if y is the largest
if ( y >= x and y >= z ):
print(str(y) + " is the greatest")
# check if x is greater than z, if so then it is the second largest number.
if ( x >= z ):
print(str(x) + " is second greatest")
else:
print(str(z) + " is second greatest")
# check if z is the largest
if ( z >= x and z >= y ):
print(str(z) + " is the greatest")
# check if x is greater than y, if so then it is the second largest number.
if ( x >= y ):
print(str(x) + " is second greatest")
else:
print(str(y) + " is second greatest")