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
  • 2
    Why would that data cause an exception to be thrown? Did you mean to use if instead? Also, == True is unnecessary. Commented Oct 4, 2019 at 12:16
  • This is not how you raise an exception - just returning False won't do. You need to raise it: stackoverflow.com/questions/2052390/… However from what you share if statement seems to be way more suitable for your purpose Commented Oct 4, 2019 at 12:19

4 Answers 4

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 🙂

Sign up to request clarification or add additional context in comments.

Comments

1

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

assert (((len(str(i)) == 10) == True) and ((float(i) > 0) == True)), "False"

Comments

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

Comments

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"

1 Comment

Also, as carcigenicate mentioned, == True is unneccessary. Also, instead of == False it might be better to use ìf not ...`. Both would increase readability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.