官术网_书友最值得收藏!

Conditional control flow: The if-statement

Conditional statements allow us to branch execution based on the value of an expression. The form of the statement is the if keyword, followed by an expression, terminated by a colon to introduce a new block. Let's try this at the REPL:

>>> if True:

Remembering to indent four spaces within the block, we add some code to be executed if the condition is True, followed by a blank line to terminate the block:

...     print("It's true!")
...
It's true!

At this point the block will execute, because self-evidently the condition is True. Conversely, if the condition is False, the code in the block does not execute:

>>> if False:
... print("It's true!")
...
>>>

The expression used with the if-statement will be converted to a bool just as if the bool() constructor had been used, so:

>>> if bool("eggs"):
... print("Yes please!")
...
Yes please!

If the value is exactly equivalent to something, we then use the if command as follows:

>>> if "eggs":
... print("Yes please!")
...
Yes please!

Thanks to this useful shorthand, explicit conversion to bool using the bool constructor is rarely used in Python.

主站蜘蛛池模板: 龙里县| 合阳县| 芦山县| 湘乡市| 长沙县| 合水县| 华容县| 黔西县| 尼木县| 镇巴县| 玉门市| 景宁| 凉山| 朝阳县| 平顺县| 呼伦贝尔市| 曲松县| 繁峙县| 宿州市| 科技| 抚州市| 衡阳县| 漯河市| 呼玛县| 永吉县| 子洲县| 隆尧县| 五家渠市| 平潭县| 敦煌市| 绵竹市| 竹北市| 大冶市| 扎鲁特旗| 崇左市| 岳西县| 元阳县| 沈丘县| 宁夏| 昆山市| 牟定县|