“在"的用法和含义在 if 语句中? [英] Use and meaning of "in" in an if statement?
问题描述
在 Zed Shaw 的 Learn Python the Hard Way 示例中,其中一个练习显示了以下代码:
next = raw_input(">")如果下一个为0"或下一个为1":how_much = int(下一个)
我很难理解这个声明中 in
的含义.我习惯使用 if
语句,例如在 javascript 中,其语法类似于:
var = 5;如果(变量> 3){//要执行的代码}
这个if
/in
语句(在python中)和javascript中的if()
一样吗?
找到这个问题的答案很棘手,因为 in
是一个很短的字符串,无法通过搜索引擎缩小答案的范围,而且我不知道其操作的正确名称.>
这取决于 next
是什么.
如果它是一个字符串(如您的示例),则 in
检查子字符串.
如果它是不同类型的可迭代对象(列表、元组、集合、字典...),则 in
检查成员资格.
在字典中,成员资格被视为键之一":
<预><代码>>>>入"入{入":出"}真的>>>入"入{出":入"}错误的In an example from Zed Shaw's Learn Python the Hard Way, one of the exercises displays the following code:
next = raw_input("> ")
if "0" in next or "1" in next:
how_much = int(next)
I'm having a hard time understanding the meaning of in
in this statement. I'm used to using if
statements, such as in javascript, where the syntax is something like:
var = 5;
if (var > 3) {
//code to be executed
}
Is this if
/ in
statement (in python) the same as if()
in javascript?
Finding an answer to this has been tricky because the in
is such a short string to narrow down an answer via search engine, and I don't know the proper name for its operation.
It depends on what next
is.
If it's a string (as in your example), then in
checks for substrings.
>>> "in" in "indigo"
True
>>> "in" in "violet"
False
>>> "0" in "10"
True
>>> "1" in "10"
True
If it's a different kind of iterable (list, tuple, set, dictionary...), then in
checks for membership.
>>> "in" in ["in", "out"]
True
>>> "in" in ["indigo", "violet"]
False
In a dictionary, membership is seen as "being one of the keys":
>>> "in" in {"in": "out"}
True
>>> "in" in {"out": "in"}
False
这篇关于“在"的用法和含义在 if 语句中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!