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
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With