如何设置变量的默认值?
How to set default value for variable?
假设我在 javascript
中有以下代码
function test(string) {
var string = string || 'defaultValue'
}
python初始化一个可能未定义的变量的方法是什么?
def test(string="defaultValue"):
print(string)
test()
您可以使用默认值:
def test(string="defaultValue")
pass
见https://docs.python.org/2/tutorial/controlflow.html#default-argument-values
在您提供的确切场景中,您可以使用参数的默认值,如其他答案所示。
通常,您可以在 Python 中使用 or
关键字,这与在 JavaScript 中使用 ||
的方式非常相似;如果有人传递了错误值(例如空字符串或 None
),您可以将其替换为默认值,如下所示:
string = string or "defaultValue"
当您的值来自文件或用户输入时,这会很有用:
string = raw_input("Proceed? [Yn] ")[:1].upper() or "Y"
或者当您想使用空容器作为默认值时,这在常规 Python 中是有问题的(参见 this SO question):
def calc(startval, sequence=None):
sequence = sequence or []
假设我在 javascript
中有以下代码function test(string) {
var string = string || 'defaultValue'
}
python初始化一个可能未定义的变量的方法是什么?
def test(string="defaultValue"):
print(string)
test()
您可以使用默认值:
def test(string="defaultValue")
pass
见https://docs.python.org/2/tutorial/controlflow.html#default-argument-values
在您提供的确切场景中,您可以使用参数的默认值,如其他答案所示。
通常,您可以在 Python 中使用 or
关键字,这与在 JavaScript 中使用 ||
的方式非常相似;如果有人传递了错误值(例如空字符串或 None
),您可以将其替换为默认值,如下所示:
string = string or "defaultValue"
当您的值来自文件或用户输入时,这会很有用:
string = raw_input("Proceed? [Yn] ")[:1].upper() or "Y"
或者当您想使用空容器作为默认值时,这在常规 Python 中是有问题的(参见 this SO question):
def calc(startval, sequence=None):
sequence = sequence or []