I have a question regarding if not
statement in Python 2.7
.
I have written some code and used if not
statements. In one part of the code I wrote, I refer to a function which includes an if not
statement to determine whether an optional keyword has been entered.
It 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 got 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 thought 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.