# Take a list of nums and return max and min

Exercise 6: Rewrite the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at the end when the user enters “done”. Write the program to store the numbers the user enters in a list and use the max() and min() functions to compute the maximum and minimum numbers after the loop completes.

num_list = []

num = input('Please enter a number: ')

while num != 'done' and num != 'DONE':
try:
num_list.append(int(num))
num = input('Please enter a number: ')
except:
num = input("Not a number. Please enter a number Or 'done' to finish: ")

try:
print('Maximum number: ', max(num_list))
print('Minimum number: ', min(num_list))
except:
print('NO INPUT!')


## 2 Answers

1. Avoid repeating yourself: use a single input call; it isn't much here, but it is easily error-prone if your "initialization" phase is several steps long. The usual idiom in such case is to use a while True loop and test the condition after the initialization to break if necessary.
2. Please avoid bare except, this is a bad habit to get into. This will catch all exceptions, including the ones you're not expecting (such as KeyboardInterrupt if the user hits Ctrl+C) and, thus, not ready to handle. In both cases, you’re expecting ValueErrors here.
3. Use functions, this will make your code much more reusable:
def ask_user_number_list():
num_list = []
while True:
num = input('Please enter a number or 'done' to finish: ')
if num.lower() == 'done':
break

try:
number = int(num)
except ValueError:
print('Invalid input')
else:
num_list.append(number)

return num_list

def search_min_and_max(lst):
try:
return min(lst), max(lst)
except ValueError:
return None

if __name__ == '__main__':
bounds = search_min_and_max(ask_user_number_list())
if bounds is None:
print('NO INPUT!')
else:
print('Maximum number: ', bounds[-1])
print('Minimum number: ', bounds)

• I just wonna say that you guys are amazing :). Thank you very much, your help means a lot for me. – Zein El Mokhtar Apr 1 at 14:27

You can use lower() on the variable to cover all possible input types,

while num:
if num.lower()=='done':
break
try:
num_list.append(int(num))
except:
print("Invalid input")
num = input('Please enter a number: ')

• The and condition is correct; or is wrong! With or, the condition is always true. – AJNeufeld Apr 1 at 5:12
• The variable num is assigned from input(), so it is always a str. The isinstance(num, str) is completely unnecessary. – AJNeufeld Apr 1 at 5:15
• And isinstance(num, int) is always false, because num is a string! – AJNeufeld Apr 1 at 5:18
• num = input(…) should be inside the while, not the except, otherwise it will keep appending the same number ad infinitum leading to a MemoryError. – Mathias Ettinger Apr 1 at 10:12
• I just wonna say that you guys are amazing :). Thank you very much, your help means a lot for me. – Zein El Mokhtar Apr 1 at 14:27