首页 > 解决方案 > 如何编写一个打印三个数字中最大数字的函数

问题描述

我需要编写一个函数来返回三个数字中最大的数字。

我用这段代码试了一下:

# The input will run until i reaches 2 (starts from 1)
# i will only get incremented when the input is valid (= is an integer) 
i = 1
while i < 2:
    try:
        x = int(input("Enter first number: "))
        y = int(input("Enter second number: "))
        z = int(input("Enter third number: "))
        i += 1
# when the input isn't valid (= is a string), the user must enter a valid value (integer)
    except ValueError:
        print("You entered a string. Try again.")


# Define the function
def max_of_three(x, y, z):
    if x > y and x > z or x == y > z or x == z > y:
        print (f"The highest number out of {x}, {y} and {z} is: ", x)
    if y > x and y > z or y == z > x:
        print (f"The highest number out of {x}, {y} and {z} is: ", y)
    if z > x and z > y:
        print (f"The highest number out of {x}, {y} and {z} is: ", z)
    if x == y == z:
        print ("All numbers are equal")


# Output function
max_of_three(x, y, z)

幸运的是,代码正在运行!但我想知道是否有任何更简单或更简单的方法来解决这个问题。

标签: pythonpython-3.x

解决方案


是的,您可以使用内置max()min()函数,如下所示:

def max_of_three(x, y, z):
    max_number = max(x,y,z)
    min_number = min(x,y,z)
    if max_number == min_number :
        print ("All numbers are equal")
    else:
        print (f"The highest number out of {x}, {y} and {z} is: ", max_number)

推荐阅读