gpt4 book ai didi

python - 通过条件语句打印用户输入的三个变量中的最大和第二大数

转载 作者:行者123 更新时间:2023-12-05 09:02:53 25 4
gpt4 key购买 nike

嘿,我最近开始学习python。下面是求最大数的程序,我想知道如何打印第二大的数。提前致谢。

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")

最佳答案

您可以通过将输入添加到列表并对其进行排序来轻松获得第二大数字。

试试这个:

xyz = [x,y,z]
sorted_xyz = sorted(xyz)
largest = sorted_xyz[-1]
second_largest = sorted_xyz[-2]

因为您希望它与条件语句一起使用。你可以试试:

# 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")

关于python - 通过条件语句打印用户输入的三个变量中的最大和第二大数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70641492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com