简体   繁体   中英

Python conventions with respect to if conditions

In python, is it frowned upon to use extra conditions within an if statement to avoid error, or should this be done separately from the if statement?

Example:

I want to make sure that d, which will be either a empty string or a number string is not blank and not less than 1. If d is a empty string, it can not be converted to a float. The statement is evaluated as false before trying to convert to float so I don't get an error. Is this bad practice?

def main(): 
    d = "2.25"
    check_d(d)
    d = "0"
    check_d(d)
    d = ""
    check_d(d)

this looks prettier to me

def check_d(d):
    if d and float(d) >= 1:
        return True
    print('d must be defined with value 1 or greater')
    return False

this was my first instinct

def check_d_old(d):
    try:
        if float(d) >= 1:
            return True
    except:
        pass
    print('d must be defined with value 1 or greater')
    return False

You don't need the if d part if you include it in the try. Something like this would work, where either you'll get a ValueError if it's not a number, or it'll raise a ValueError if it is a number but under 1.

def check_d(d):
    try:
        if float(d) >= 1:
            return 0
        else:
            raise ValueError()
    except ValueError:
        print('d must be defined with value 1 or greater')
        return 1

It's fine using extra conditions, but if you can skip a few unnecessary ones, it'll run faster overall. Also, try to not just use except , find out which type of error you want to be looking for.

The first is fine assuming that d will always fit your criteria but the second example is more robust.

For example when d = "a" the condition if d and float(d) >= 1: will raise the ValueError where as the try: except will catch it and work properly.

So if your criteria of "d will be either a blank string or a number string" is absolute then the first is fine, however if d could have other values then you may want to use the second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM