0

Hi I am pulling a variable, call it x, from urllib.request.urlopen

I then want to make a float comparison.

However, as this variable can vary, and be unavailable, it is occasionally "N/A"

this is my comparison

    x = (sourceCode.split)('sourcesnippet1')[1].split('sourcesnippet2')[0]
    if 0 < float(x) < 1:
        print (entity, 'meets requirements')
        print (x)

how can I make it so that pseudo:

chek = 'N/A'
            x = (sourceCode.split)('sourcesnippet1')[1].split('sourcesnippet2')[0]
if str(x) == chek TRUE, then go to next query
else
            if 0 < float(x) < 1:
                print (entity, 'meets requirements')
                print (x)

1 Answer 1

2

Don't use if at all, just try convert it to float, and catch exception:

parts = (sourceCode.split)('sourcesnippet1')
txt = parts[1].split('sourcesnippet2')[0]
try:
    x = float(txt)
except ValueError as err:
    print(err)
    continue
print ("Now I know, that I have a valid float...")
# do your stuff

This is prevalent style in Python, see https://docs.python.org/2/glossary.html#term-eafp

You can also guard against other errors, like .split() returning just one element:

parts = (sourceCode.split)('sourcesnippet1')
try:
    txt = parts[1].split('sourcesnippet2')[0]
    x = float(txt)
except (ValueError, LookupError) as err:
    print(err)
    continue
Sign up to request clarification or add additional context in comments.

Comments

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.