Python学习笔记(十一)- if 测试和语法规则(if Tests and Syntax Rules)

1.如何用Python编写多路分支?
答:一个带有多个elif子句的if语句通常是最直接的方法,来编写多路分支,虽然不一定是最简洁或最灵活的。字典索引通常取得相同的结果,尤其是当字典包含用 def 语句或 lambda 表达式编写的可调用函数时。

2.如何在Python中将 if/else 语句编写为表达式?
答:在Python 2.5 和 之后的版本,表达式 Y if X else Z ,当X为True,返回Y,否则返回Z;这和四行的if语句具有相同的效果。and/or 结合【 ((X and Y) or Z) 】可以起到同样的效果,但是这看上去更加模糊,而且需要Y部分为真值。

3.如何让单个语句跨越多行?
答:把语句用开放的句法对【 (), [] 或者 {} 】包裹起来之后,它可以跨越任意多行;语句结束,当 Python 看见结束(右半边)的括号对,语句第2行及其后面可以在任何缩进级别开始。反斜杠连续(Backslash continuations)也能起作用,但在Python世界中普遍不受欢迎。

4.True 和 False 的意思是什么?
答:True 和False 分别是整数1和0的自定义版本:它们通常在 Python 代表布朗值的 True 和 False 。它们可用于真值测试和变量初始化,并在交互式提示符下打印表达式结果。在所有这些扮演角色中,它们起着更多的助记性作用,因此也是一种可读的替代1和0的可选方法。

标注:转载《Learning Python 5th Edition》[奥莱理]

1. How might you code a multiway branch in Python?
2. How can you code an if/else statement as an expression in Python?
3. How can you make a single statement span many lines?
4. What do the words True and False mean?

1. An if statement with multiple elif clauses is often the most straightforward way to code a multiway branch, though not necessarily the most concise or flexible. Dictionary indexing can often achieve the same result, especially if the dictionary contains callable functions coded with def statements or lambda expressions.
2. In Python 2.5 and later, the expression form Y if X else Z returns Y if X is true, or Z otherwise; it’s the same as a four-line if statement. The and/or combination (((X and Y) or Z)) can work the same way, but it’s more obscure and requires that the Y part be true.
3. Wrap up the statement in an open syntactic pair ((), [], or {}), and it can span as many lines as you like; the statement ends when Python sees the closing (right) half of the pair, and lines 2 and beyond of the statement can begin at any indentation level. Backslash continuations work too, but are broadly discouraged in the Python world.
4. True and False are just custom versions of the integers 1 and 0, respectively: they always stand for Boolean true and false values in Python. They’re available for use in truth tests and variable initialization, and are printed for expression results at the interactive prompt. In all these roles, they serve as a more mnemonic and hence readable alternative to 1 and 0.

猜你喜欢

转载自blog.csdn.net/Enderman_xiaohei/article/details/87439318
今日推荐