Python 程序查找三个数中的最大值

编写一个 Python 程序,使用 Elif 语句和嵌套 If 语句查找三个数中的最大值。有多种方法可以找到三个数中的最大数,我们将一一讨论。

Python 程序使用 elif 语句查找三个数中的最大值

此程序帮助用户输入三个不同的值。接下来,此程序将使用 elif 语句查找这三个数中的最大值。

# using elIf Statement
a = float(input("Please Enter the First value: "))
b = float(input("Please Enter the First value: "))
c = float(input("Please Enter the First value: "))

if (a > b and a > c):
          print("{0} is Greater Than both {1} and {2}". format(a, b, c))
elif (b > a and b > c):
          print("{0} is Greater Than both {1} and {2}". format(b, a, c))
elif (c > a and c > b):
          print("{0} is Greater Than both {1} and {2}". format(c, a, b))
else:
          print("Either any two values or all the three values are equal")

首先,我们输入值为 a = 12, b = 4, c = 6。接下来,我们输入值为 a = 19, b = 25, c = 20。接下来,我们输入值为 a = 45, b = 36, c = 96。最后,我们输入值为 a = 5, b = 5, c = 5。

上述查找三个数中最大值的程序示例的输出如下。

Program to Find Largest of Three numbers using elif Statement

在此 Python 程序中查找最大值,前三行代码要求用户输入三个数字,并将用户输入的值存储在变量 a、b 和 c 中。

在此 程序 中,第一个 if 条件检查 a 是否大于 b 且 a 是否大于 c。如果两者都为 True,则将显示以下打印语句(a 大于 b 和 c)。

if (a > b and a > c):
          print("{0} is Greater Than both {1} and {2}". format(a, b, c))

第一个 Elif 语句 检查 b 是否大于 a 且 b 是否大于 c。如果两者都为 True,则将显示以下打印语句(b 大于 a 和 c)。

elif (b > a and b > c):
          print("{0} is Greater Than both {1} and {2}". format(b, a, c))

第二个 Elif 语句检查 c 是否大于 a 且 c 是否大于 b。如果两者都为 True,则将显示以下打印语句(c 大于 a 和 b)。

elif (c>a and c>b):
          print("{0} is Greater Than both {1} and {2}". format(c, a, b))

如果以上所有 Python 条件都失败,则表示它们相等。

print("Either any two values or all the three values are equal")

Python 程序查找三个数中的最大值使用数字嵌套 If 语句

此程序帮助用户输入三个不同的值。接下来,此程序将使用嵌套 If 语句查找这三个数中的最大值。

# using Nested If Statement
a = float(input("Please Enter the First value: "))
b = float(input("Please Enter the First value: "))
c = float(input("Please Enter the First value: "))

if (a-b > 0) and (a-c > 0):
    print("{0} is Greater Than both {1} and {2}". format(a, b, c))
else:
    if(b - c > 0):
        print("{0} is Greater Than both {1} and {2}". format(b, a, c))
    else:
        print("{0} is Greater Than both {1} and {2}". format(c, a, b))

在此查找三个数中最大值的程序中,首先,我们输入值 a= 32, b= 45, c= 98。接下来,我们输入值 a= 22, b= 5, c= 7。最后,我们输入值 a= 56, b= 222, c= 98。

Python Program to Find Largest of Three numbers using Nested if

在此 Python 程序中查找最大值,前三个语句要求用户输入三个数字,并将用户输入的值存储在变量 a、b 和 c 中。

第一个 if 条件检查 a-b 是否大于 0 且 a-c 是否大于 0。如果我们从大数中减去小数,此条件将失败。否则,它将为 True。如果此条件为 True,则 a 大于 b 和 c。

if (a-b> 0) and (a-c > 0):
    print("{0} is Greater Than both {1} and {2}". format(a, b, c))

Else 语句将在第一个 If 条件为 False 时执行,因此无需检查值。在 Else 语句中,我们插入另一个 if 条件(嵌套 If)来检查 b-c 是否大于 0。如果此条件为 True,则 b 大于 a 和 c。

else:
    if(b- c> 0):
        print("{0} is Greater Than both {1} and {2}". format(b, a, c))

否则 c 大于 a 和 b。

print("{0} is Greater Than both {1} and {2}". format(c, a, b))

评论已关闭。