12

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?

Sebastian Paaske Tørholm
  • 47,464
  • 10
  • 95
  • 116
user3619165
  • 260
  • 1
  • 2
  • 11
  • The answers tell you how to have a parameter with a default value, but maybe you want this: http://stackoverflow.com/questions/23086383/how-to-test-nonetype-in-python – Paulo Almeida Mar 30 '16 at 23:16

3 Answers3

16

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 []
kindall
  • 168,929
  • 32
  • 262
  • 294
5
def test(string="defaultValue"):
    print(string)

test()
ruthless
  • 299
  • 3
  • 12
1

You can use default values:

def test(string="defaultValue")
    pass

See https://docs.python.org/2/tutorial/controlflow.html#default-argument-values

Dominic K
  • 6,775
  • 10
  • 51
  • 62