0

I'm trying to validate an input in Python that needs to be both ten digits long and a non-negative number. I thought I'd use a couple try-catch statements to do so, but even when the output fits an exception, the exception ain't being triggered

i = input("Please input a value: ")
try:
    (len(str(i)) == 10) == True
except:
    print("False")
try:
    (float(i) > 0) == True
except:
    print("False")

I'm expecting it to simply return "False" when I insert something like "123" or "-1029347365", but there's no output

  • 2
    Why would that data cause an exception to be thrown? Did you mean to use `if` instead? Also, `== True` is unnecessary. – Carcigenicate Oct 04 '19 at 12:16
  • This is not how you raise an exception - just returning ```False``` won't do. You need to ```raise``` it: https://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python However from what you share ```if``` statement seems to be way more suitable for your purpose – Grzegorz Skibinski Oct 04 '19 at 12:19

4 Answers4

1

I agree with the previous answer, this will do the trick:

assert (((len(str(i)) == 10) == True) and ((float(i) > 0) == True)), "False"
im2527
  • 391
  • 3
  • 4
1

If you're set on using a try catch, which can come in handy. You could always create your own exception classes.

What your looking to do can be accomplished with a simple if statement such as

if not (( len(str(i)) == 10) and (float(i) > 0)):
    #do something

but I'm assuming you might have a reason for using Try catch. Here's a link that might be helpful for you. https://www.programiz.com/python-programming/user-defined-exception

1
i = input()
if len(str(i)) == 10:
  print("true")
else:
  print("False")

if float(i) > 0:
    print("true")
else:
    print("False")

simple enough... hope it helps

if you want to raise the exceptions you can opt the previous answers

0

try ... except only works, when your code produce an exception. In your case, you only compare two statements and the result might be True or False. To make it work, you could put it in:

if (len(str(i)) == 10) == False :
    raise

(to manually raise an exception if your statement is False), or better use assert:

# assert <condition>,<error message>
assert (float(i) > 0) == True, "False"
natter1
  • 354
  • 2
  • 10
  • Also, as carcigenicate mentioned, `== True ` is unneccessary. Also, instead of `== False` it might be better to use ìf not ...`. Both would increase readability. – natter1 Oct 04 '19 at 12:43