Python技术问询:如何通过条件语句实现用户输入三个数值的最大值及第二最大值输出
Hey there! Let's tweak your Python program to find both the greatest and second-greatest number from those three inputs you're working with. I'll stick with the conditional statement style you're already using—no fancy built-in shortcuts, just straightforward checks that match your original code's vibe.
Modified Program to Get Greatest & Second-Greatest Numbers
Here's the adjusted code that does exactly what you need:
x = int(input("Enter the 1st number: \n")) y = int(input("Enter the 2nd number: \n")) z = int(input("Enter the 3rd number: \n")) # Step 1: Figure out which is the greatest number if x > y and x > z: greatest = x # Now check the remaining two for second greatest second_greatest = y if y > z else z elif y > x and y > z: greatest = y second_greatest = x if x > z else z else: greatest = z second_greatest = x if x > y else y # Output both results print(f"{greatest} is the greatest number") print(f"{second_greatest} is the second greatest number")
How this works:
- First, we use chained conditionals to identify which of the three numbers is larger than the other two—this gives us our maximum value.
- Once we know the greatest number, the second largest has to be the bigger of the two leftover numbers. We just do a quick check between those two to get our runner-up.
If you prefer a slightly more compact version (still using only conditionals), you could write it like this instead:
x = int(input("Enter the 1st number: \n")) y = int(input("Enter the 2nd number: \n")) z = int(input("Enter the 3rd number: \n")) # Calculate greatest with ternary conditionals greatest = x if (x > y and x > z) else (y if y > z else z) # Calculate second greatest based on which number was the max second_greatest = y if (greatest == x and y > z) else (z if greatest == x else x if (greatest == y and x > z) else z if greatest == y else x if x > y else y) print(f"{greatest} is the greatest") print(f"{second_greatest} is the second greatest")
This does the exact same job, just wraps some of the checks into one-liner conditionals. Either version will work perfectly for your requirement.
内容的提问来源于stack exchange,提问作者Bhaskar baswala




