-3
largest = None
smallest = None
l = []
while True:
    try:
        num = input("Enter a number: ")
    except NameError as err:
        if err == "done":
            break
        else:
            print("Invalid input")
    finally:
        l.append(num)
        l.sort()
        largest = l[-1]
        smallest = l[0]


print("Maximum", largest)
print("Minimim", smallest)
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
  • 3
    how is the `except` every going to be triggered? – SuperStew Feb 11 '20 at 02:27
  • 2
    Why use finally at all? Why not sort and calculate the smallest/largest in the "done" processing? – jarmod Feb 11 '20 at 02:27
  • 1
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – wjandrea Feb 11 '20 at 02:28
  • You need to redesign your logic. A `NameError` will never happen, and it will never be equal to `'done'`. As well, `l.sort()` and everything after should be outside of the loop. – wjandrea Feb 11 '20 at 02:29
  • no cuz' he uses ValueError and I want to use NameError as exception – Anas Ghareib Feb 11 '20 at 02:33
  • If your objective is to get the smallest and largest, uou can just use 2 variables, current min and current max. There is no need for the list and sort. – maxhuang Feb 11 '20 at 02:38

2 Answers2

3

This code looks like it's for Python 2.x, where input() tried to evaluate the input, and signalled an error if you typed a string that's not a variable name. Python 3.x doesn't signal an error when you type done.

So just compare the input. You can later do error checking when you try to convert it to an int.

while True:
    num = input("Enter a number")
    if num == "done":
        break
    try:
        num = int(num)
    except ValueError:
        print("Invalid input")
        continue
    l.append(num)
l.sort()
largest = l[-1]
smallest = l[0]
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Refactored logic. NameError won't happen and finally not needed...just put it outside the while when "finally" done.

nums = []

while True:
    num = input('Enter a number or "done": ')  # num is a string at this point
    if num == 'done':
        break
    try:
        # try to convert num to integer...
        num = int(num)  # This can fail with ValueError, so is in try
        nums.append(num)   # This won't run if above raises exception
    except ValueError:
        print("Invalid input")

# No need to sort...
print("Maximum", max(nums)) 
print("Minimum", min(nums))
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251