Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Assign Value if None Exists

I am a RoR programmer new to Python. I am trying to find the syntax that will allow me to set a variable to a specific value only if it wasn't previously assigned. Basically I want:

# only if var1 has not been previously assigned  var1 = 4 
like image 351
Spencer Avatar asked Sep 07 '11 18:09

Spencer


People also ask

How can we set default value to the variable in Python?

Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.

How do you check if a value is not None in Python?

Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).

What is the difference between None and null in Python?

null is often defined to be 0 in those languages, but null in Python is different. Python uses the keyword None to define null objects and variables. While None does serve some of the same purposes as null in other languages, it's another beast entirely.


1 Answers

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.

like image 52
Anurag Uniyal Avatar answered Sep 18 '22 19:09

Anurag Uniyal