-1

How can I check whether the inputted character is number or not and wanted to raise an error for the same in python?

class Error(Exception):
  pass
class ValueTooSmallError(Error):
  pass
class ValueTooLargeError(Error):
  pass
class ValueError(Error):
  pass

number = 10
while True:
    try:
            i_num = float(input("Enter a number: "))
            if i_num < number:
                raise ValueTooSmallError
            elif i_num > number:
                raise ValueTooLargeError
                break
        except ValueTooSmallError:
            print("This value is too small, try again!")
            print()
        except ValueTooLargeError:
            print("This value is too large, try again!")
            print()
        except ValueError: **`this error doesn't reflect`**
            print("Input is not a number")
            print()
    print("Congratulations! You guessed it correctly.")
    ```
Sudip
  • 3
  • 4
  • I am raising exception and also printed statement but I am unable to put the condition for the same. – Sudip May 02 '22 at 10:40

2 Answers2

0

If the input is not a number, it raises ValueError. As such, adding another except statement to catch a ValueError would catch the case when the inputted string is not proper float.

fourjr
  • 329
  • 2
  • 9
  • Still it doesn't work in the code. – Sudip May 03 '22 at 05:46
  • I believe this is because you are *redefining* `ValueError` in your own code. `ValueError` is a standard exception provided by Python for catching incorrect string-to-number errors (and others), but your own definition of `ValueError` is masking it, so that you can't catch the one that Python is throwing. Just remove your definition of `ValueError`. – Derek T. Jones May 03 '22 at 05:59
0

As you are typecasting the given input to float, that statement it self throws an error if given input is not a number. Ex: float('a') gives following error "ValueError: could not convert string to float: 'a'". So you need to add that exception in your code.

user3539644
  • 3
  • 1
  • 5