Python: Assign Value if None Exists
Solution 1:
You should initialize variables to None and then check it:
var1 = None
if var1 is None:
var1 = 4
Which can be written in one line as:
var1 = 4 if var1 is None else var1
or using shortcut (but checking against None is recommended)
var1 = var1 or 4
alternatively if you will not have anything assigned to variable that variable name doesn't exist and hence using that later will raise NameError
, and you can also use that knowledge to do something like this
try:
var1
except NameError:
var1 = 4
but I would advise against that.
Solution 2:
var1 = var1 or 4
The only issue this might have is that if var1 is a falsey value, like False or 0 or [], it will choose 4 instead. That might be an issue.