Sudip
Sudip

Reputation: 1

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

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.")
    ```

Upvotes: -1

Views: 40

Answers (2)

Saikumar Kodakandla
Saikumar Kodakandla

Reputation: 3

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.

Upvotes: 0

fourjr
fourjr

Reputation: 329

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.

Upvotes: 0

Related Questions