alphanumeric
alphanumeric

Reputation: 19329

When zero is not None or not False but digit 0

In the example below result will be assigned to var2 since var1 is None:

var1=None
var2='June'
result=var1 or var2

But if var1 is zero result is still assigned to var2 because zero is considered to be the same as None or False:

var1=0
var2='June'
result=var1 or var2

How (without using if var1!=None) to edit this code to make sure var1 is considered to be "valid"(not None, not False) even if its value is zero 0?

Upvotes: 0

Views: 305

Answers (1)

Ray Toal
Ray Toal

Reputation: 88378

While or looks pretty, it looks like you might want to go with this:

result = var1 if var1 is not None else var2

Remember in Python there are a lot of things that are falsy: 0, False, None, '', empty sequences, empty mappings, and instances of classes with __nonzero__ and __len__ set a certain way.

The code above allows all those things except None to give you var1. Adjust accordingly.

ADDENDUM

For example, in Ruby, only nil and false are falsy. Let's say you want to duplicate this behavior in Python. You could write:

result = var1 if var1 is not None and var1 is not False else var2

However, here is a warning. Do NOT write:

result = var1 if var1 not in [None,False] else var2  # FAIL! DOES NOT WORK!!!!!!

Why? Because, in Python 2 at least:

>>> 0 is None
False
>>> 0 is False
False
>>> 0 in [None,False]
True
>>> 0 in [False]
True
>>> 0 == None
False
>>> 0 == False
True

Good to know, especially if one is moving to Python from Ruby.

Upvotes: 5

Related Questions