Python max和min

时间:2011-12-15 19:21:06

标签: python max min

我对Python很陌生,让我对我的问题感到愤怒的是,我觉得它很简单。我在第8行继续收到错误。我只是希望这个程序能够获取用户输入的数字和打印最大和最小,如果它们输入负1,我希望它取消循环。

'int' object is not iterable是错误。

print "Welcome to The Number Input Program."

number = int(raw_input("Please enter a number: "))

while (number != int(-1)):
    number = int(raw_input("Please enter a number: "))

high = max(number)
low = min(number)

print "The highest number entered was ", high, ".\n"
print "The lowest number entered was ", low, ".\n"

raw_input("\n\nPress the enter key to exit.")

5 个答案:

答案 0 :(得分:17)

问题是numberintmaxmin都需要列表(或其他可迭代的内容) - 相反,您必须将number添加到列表中,如下所示:

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

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

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

在阅读jimbob博士答案后的一个注释 - 我的回答是假设您想要在找到highlow时考虑-1。

答案 1 :(得分:8)

这是因为每次将一个整数参数传递给max和min并且python不知道如何处理它。

Ether传递至少两个参数:

least_number = min(number1, number2,...,numbern)

或可迭代的:

least_number = min([number1, number2, ...,numbern])

这是doc

答案 2 :(得分:1)

您需要将数字更改为数字列表。如,

print "Welcome to The Number Input Program."

numbers = []
number = int(raw_input("Please enter a number: "))

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

high = max(numbers)
low = min(numbers)

print "The highest number entered was ", high, ".\n"
print "The lowest number entered was ", low, ".\n"

raw_input("\n\nPress the enter key to exit.")

答案 3 :(得分:0)

another answer所述,minmax也可以使用多个参数。要省略列表,您可以

print "Welcome to The Number Input Program."

number = int(raw_input("Please enter a number: "))
high = low = number


while (number != int(-1)):
    number = int(raw_input("Please enter a number: "))
    high = max(high, number)
    low = min(low, number)

print "The highest number entered was ", high, ".\n"
print "The lowest number entered was ", low, ".\n"

raw_input("\n\nPress the enter key to exit.")

答案 4 :(得分:0)

Popup