查找最大和最小

时间:2019-05-17 13:07:09

标签: python

我正在尝试编写一个Python程序,该程序向用户请求五个整数值。然后打印输入的最大值和最小值。

#Program to print max and min

number = int(input("Please enter a number: "))
num_list = []

while (number != int(-1)):
    num_list.append(number)
    number = int(input("Please enter a number: "))

high = max(num_list)
low = min(num_list)

如何将输入数量限制为5?

4 个答案:

答案 0 :(得分:4)

# Create the number list
num_list = []
# Iterate 5 times:
# '_' means that we don't want to use this variable
# range(5) returns iterator (0,1,2,3,4) (with length=5)
for _ in range(5):
    # Get input
    # It can raise an error, I don't check it
    number = int(input("Please enter a number: "))
    # If the number is equal to -1
    if number == -1:
        # We exit from the loop
        break
    # If we didn't exit, we add number to num_list
    num_list.append(number)

high = max(num_list)
low = min(num_list)

您将尝试获得五个数字。如果其中之一等于-1,您将退出循环。

答案 1 :(得分:2)

使用while循环

num_list = []
counter = 0
while counter < 5:
    number = int(input("Please enter a number: "))
    if number == -1:
        break
    counter += 1
    num_list.append(number)

high = max(num_list)
low = min(num_list)

答案 2 :(得分:1)

num_list = []
while len(num_list) < 5:
    number = int(input("Please enter a number: "))
    if number == -1:
        break
    num_list.append(number)

high = max(num_list)
low = min(num_list)

答案 3 :(得分:0)

效果很好。

values = str(input("Enter Five values comma(,) separted :")).split(',')
print(f'Max : {max([int(x) for x in values])}\nMin : {min([int(x) for x in values])}')