Steve Smith Steve Smith - 10 months ago 52
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
return z

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

Answer Source

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!