mardi 23 février 2016

If not statement with 0.0

I have a questions regarding if not statements in python 2.7. I have written some code and used if not statements where possible. However, in one of the ode I have, I refer to a functions which includes if not statement to determine whether an optional keyword has been entered. This works fine, except when 0.0 is the keyword's value. I understand this is because 0 is one of the things that is considered 'not'.

My code is probably too long to post, but this is an analogous (albeit simplified) example:

def square(x=None):
    if not x:
        print "you have not entered x"
    else:
        y=x**2
        return y

list=[1, 3, 0 ,9]
output=[]


for item in list:
    y=square(item)
    output.append(y)

print output

However, in this case I get left with:

you have not entered x
[1, 9, None, 81]    

Where as I would like to get:

[1, 9, 0, 81]

In the above example I could use a list comprehension, but assuming I wanted to use the function and get the desired output how could I do this.

One though I had was:

def square(x=None):
    if not x and not str(x).isdigit():
        print "you have not entered x"
    else:
        y=x**2
        return y

list=[1, 3, 0 ,9]
output=[]


for item in list:
    y=square(item)
    output.append(y)

print output

This works, but seems like a bit of a clunky way of doing it. If anyone has another way that would be nice I would be very appreciative. Many thanks

Aucun commentaire:

Enregistrer un commentaire