Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python max and min

Tags:

python

max

min

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.")
like image 849
Speedy Bast Avatar asked Dec 15 '11 19:12

Speedy Bast


People also ask

How do you find the max and min in Python?

Use Python's min() and max() to find smallest and largest values in your data. Call min() and max() with a single iterable or with any number of regular arguments. Use min() and max() with strings and dictionaries.

Do the MAX () and MIN () functions work with strings?

The min() and max() methods can also be used to find the smallest and largest characters in a string. In this case, smallest and largest refer to the position of the character in the alphabet.

What is the use of MAX () and MIN ()?

SQL MIN() and MAX() FunctionsThe MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.

What does Max () do in Python?

Python max() Function The max() function returns the item with the highest value, or the item with the highest value in an iterable.


1 Answers

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.

like image 132
Nate Avatar answered Sep 30 '22 20:09

Nate