Steve Smith Steve Smith - 21 days ago 11
Python Question

What does "if condition" mean, when the condition is not a statement?

I'm learning about functions at the moment, and this one came up as an example:

def a(x, y, z):
if x:
return y
else:
return z


I'm not exactly sure what
if x
actually means, though.
x
is just a parameter, not a statement, so how can it be true or false?

Answer

It checks if x is "truthy", which means that it shouldn't be :

  • None
  • False
  • Zero
  • Empty

As an example :

if 1 and True and "string" and ["list"] and {'key' : 'value'} and\
    not None and not 0 and not False and not "" and not [] and not {}:
  print "I understood truthiness!"
# => I understood truthiness!