如何在不使用循环的情况下找到(三个值)的最大值? [蟒蛇]

时间:2018-09-17 02:46:06

标签: python

我是编程的新手,这让我绊了脚,我一直在想做这样的事情,但我做不到

num1 = int(input('What is the first number?:'))
num2 = int(input('What is the second number?:'))
num3 = int(input('What is the third number?:'))

[[[此后,我开始思考elif语句并使用[and,or]]

3 个答案:

答案 0 :(得分:0)

将所有variables添加到list中,然后您就可以像这样max那样使用max(lista)函数

num1 = int(input('What is the first number?: '))
num2 = int(input('What is the second number?: '))
num3 = int(input('What is the third number?: '))

lista = [num1, num2, num3]

biggest = max(lista)

print(f"{biggest} is the largest value.")
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 max.py
What is the first number?: 10
What is the second number?: 3
What is the third number?: 8
10 is the largest value.

仅需一点奖励,它不包括处理TypeErrors,但想给您一些想法,让您可以在这个小项目中进行尝试:

while True:

    numbers = int(input("How many numbers would you like to enter: "))

    values = []

    for i in range(numbers):
        if i == numbers - 1:
            values.append(int(input(f"Enter 1 number: ")))
        else:
            values.append(int(input(f"Enter {numbers - i} numbers: ")))

    print(f"\nThe largest number entered was {max(values)}")
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 max.py
How many numbers would you like to enter: 5
Enter 5 numbers: 10
Enter 4 numbers: 8
Enter 3 numbers: 29
Enter 2 numbers: 13
Enter 1 number: 22

The largest number entered was 29

答案 1 :(得分:0)

Python的max(list)为您完成工作。

如果您希望创建一个可以接受任意数量输入的函数,则可以创建这样的函数。

def my_function(*args):
    return max(args)

答案 2 :(得分:0)

num1=int(input('What is the first number?:'))
num2=int(input('What is the second number?:'))
num3=int(input('What is the third number?:'))
if(num1>num2 and num1>num2):
    print(num2, 'is the largest value')
elif(num2>num1 and num2>num3):
    print(num2, 'is the largest value')
else:
    print(num3, 'isenter code here the largest value')