Python max and min

ぐ巨炮叔叔 提交于 2019-12-08 19:16:27

问题


I'm pretty new to Python, and what makes me mad about my problem is that I feel like it's really simple.I keep getting an error in line 8. I just want this program to take the numbers the user entered and print the largest and smallest, and I want it to cancel the loop if they enter negative 1.

'int' object is not iterable is the error.

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.")

回答1:


The problem is that number is an int. max and min both require lists (or other iterable things) - so instead, you have to add number to a list like so:

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)

Just as a note after reading dr jimbob's answer - my answer assumes that you don't want to account for -1 when finding high and low.




回答2:


That's cause each time you pass one integer argument to max and min and python doesn't know what to do with it.

Ether pass at least two arguments:

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

or an iterable:

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

Here's the doc




回答3:


You need to change number to an list of numbers. E.g.,

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.")



回答4:


As mentioned by another answer, min and max can also take multiple arguments. To omit the list, you can

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.")


来源:https://stackoverflow.com/questions/8525447/python-max-and-min

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!