0

By using the while loop get numbers as input from the user and add them to the list. If the user enters 'done' then the program output maximum and minimum number from the list.

This code also includes the error message using the 'try and except' block for wrong inputs.

nums = list()
while(True):
    x = input("Enter a Number: ")  
    if x == "done":
        break
    try:
        inp = float(x)
        nums.append(inp)
    except:
        print("Enter only numbers or type 'done'")
        continue
print("Maximum: ", max(nums))
print("Minimum: ", min(nums))

Input: 1, 2, 3, 4, er, done,...

Issue: 'er' input did not call except block, instead kept taking inputs. Somehow the Program was still running even after typing 'done' and kept taking input.

Tried: Added print(x) after line:3 but did not get any output for that either.

Jay
  • 11
  • 3
  • 3
    I'm surprised this doesn't work for you - try displaying `x` after `input()` to see what you have (this will also help, for example, if you're really running a different file than you expect) – ti7 Oct 27 '22 at 00:08
  • 1
    your code works for me – bn_ln Oct 27 '22 at 00:08
  • 1
    Cannot reproduce the issue. Seems to be working as expected. Have you checked that the intendation is correct in your code? – Mushroomator Oct 27 '22 at 00:08
  • I can't reproduce the issue. If I input `5`, `6`, `y`, `done`, it works as expected including saying that `y` is not a number. Maybe you're running the wrong script? Please make a [mre]. BTW, welcome to Stack Overflow! Please take the [tour]. Check out [ask] if you want more tips. – wjandrea Oct 27 '22 at 00:10
  • 1
    FWIW though, [a bare `except` is bad practice](/q/54948548/4518341). Instead, use the specific exception you're expecting like `except ValueError`, or at least `except Exception`. Plus, `nums.append()` can't fail AFAIK, so keep that out of the `except` block. – wjandrea Oct 27 '22 at 00:11
  • maybe you type some extra char (space which you can't see) or maybe you use `Done` instead of `done`. It may be good to use `x = x.strip().lower()`. You could also use `print(x)` and `print( x == 'done' )` to check what you really have in variable. OR even `print(f'>{x}<')` to see if there are some spaces. – furas Oct 27 '22 at 00:12
  • Maybe first use `print()` (and `print(type(...))`, `print(len(...))`, etc.) to see which part of code is executed and what you really have in variables. It is called `"print debuging"` and it helps to see what code is really doing. – furas Oct 27 '22 at 00:14
  • 3
    @furas Instead of `print(f'>{x}<')`, I'd recommend `print(f'{x = }')`. It'll show the variable name and its repr. Great for debugging! You could even show the `ascii` repr with `print(f'{x = !a}')`. – wjandrea Oct 27 '22 at 00:15
  • I ran the code again and surprisingly it works fine. Also debugging code worked fine. Also edited my question according to the guideline but not sure if i did it correctly. – Jay Oct 27 '22 at 23:17

0 Answers0