Search code examples
pythonundefined

How to set default value for variable?


Imagine I have the following code in javascript

function test(string) {
    var string = string || 'defaultValue'
}

What is the Python way of initiating a variable that may be undefined?


Solution

  • In the exact scenario you present, you can use default values for arguments, as other answers show.

    Generically, you can use the or keyword in Python pretty similarly to the way you use || in JavaScript; if someone passes a falsey value (such as a null string or None) you can replace it with a default value like this:

    string = string or "defaultValue"
    

    This can be useful when your value comes from a file or user input:

    string = raw_input("Proceed? [Yn] ")[:1].upper() or "Y"
    

    Or when you want to use an empty container for a default value, which is problematic in regular Python (see this SO question):

    def calc(startval, sequence=None):
         sequence = sequence or []