使用If-Else梯子查找输入的四个数字中的最大值



(这里绝对是新手,所以请原谅我)

我的任务是找出用户在python程序中输入的四个数字中的最大值。

我使用了以下语法…

a = int(input("enter first number"))
b = int(input("enter second number"))
c = int(input("enter third number"))
d = int(input("enter fourth number"))
if(a>b, a>c, a>d):
print(a)
elif(b>a, b>c, b>d):
print(b)
elif(c>a, c>b, c>d):
print(c)
else:
print(d)

此操作无效。

然而,当我在上面的梯子中只使用'if'条件时,它按预期工作。当a=1, b=2, c=3, d=4时,它不会打印'a',当a=4, b=3, c=2, d=1时,它会打印'a'。我尝试了更多四个数字的组合,代码就像我想的那样工作。

为什么完整的语法不工作,因为它只做了'if'条件到位?

完成任务的另一种方法是什么?

编辑:我在工作中观察我的程序时犯了一个错误。当我只使用这部分代码时。
a = 1
b = 2
c = 3
d = 4
if(a>b , a>c , a>d):
print(a)

在这种情况下,程序也会输出'a'。抱歉,如果原来的帖子造成了任何混乱。感谢@chepner,他的回复促使我重新完成这个程序。

您可以这样做,例如将任何数字视为最大值,然后简单地比较其余数字以找出其中的最大值

max_ = a
if b > max_:
max_ = b
if c > max_:
max_ = c
if d > max_:
max_ = d
print(max_)
a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
c = int(input("Enter Third Number: "))
d = int(input("Enter Fourth Number: "))

if a > b and a > c and a > d:
print(a)
elif b > a and b > c and b > d:
print(b)
elif c > a and c > b and c > d:
print(c)
elif d > a and d > b and d > c:
print(d)

应该使用

最简单的解决方案是使用max:

print(max(a, b, c, d))

这个想法是将用户输入添加到一个列表中,并使用max来查找最大

lst = []
for i in range(0,4):
x = int(input("enter a number:"))
lst.append(x)
print(max(lst))
import math
def maximumoffour(i,j,k,l):
m=max(i,j,k,l)
print("Maximum of the given four numbers",i,j,k,l, "is",m)
i=eval(input("enter the value 1 :"))
j=eval(input("enter the value 2 :"))
k=eval(input("enter the value 3 :"))
l=eval(input("enter the value 4 :"))
maximumoffour(i,j,k,l)