Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 239
user3619165 Avatar asked Mar 30 '16 23:03

user3619165


People also ask

How do you assign a default value to a variable?

${var:-word} If var is set and not empty, substitute the value of var; otherwise substitute word. ${var:=word} If var is not set or is empty, set it to word; then substitute the value of var (that is, if $var does not exist, set $var to $word and use that).

How do you assign a default value to a variable in Python?

The default value is assigned by using the assignment(=) operator of the form keywordname=value.

Can we set default values for variables in Java?

Core Java bootcamp program with Hands on practice Therefore, In Java default values for local variables are not allowed.

What is the default value of variable?

Variables of any "Object" type (which includes all the classes you will write) have a default value of null. All member variables of a Newed object should be assigned a value by the objects constructor function.


2 Answers

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 []
like image 102
kindall Avatar answered Sep 19 '22 16:09

kindall


def test(string="defaultValue"):
    print(string)

test()
like image 36
ruthless Avatar answered Sep 16 '22 16:09

ruthless