簡體   English   中英

如何編寫打印三個數字中最大數字的 function

[英]How to write a function that prints the highest number out of three numbers

我需要編寫一個 function ,它將返回三個數字中的最高數字。

我用這段代碼試了一下:

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

幸運的是,代碼正在運行。 但我想知道是否有任何更簡單或更簡單的方法來解決這個問題。

是的,您可以使用內置的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM