- The Python Apprentice
- Robert Smallshire Austin Bingham
- 195字
- 2021-07-02 22:16:55
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.
- Implementing Modern DevOps
- JavaScript高效圖形編程
- JavaScript:Functional Programming for JavaScript Developers
- Learning Spring 5.0
- 深入實(shí)踐Spring Boot
- Django Design Patterns and Best Practices
- VSTO開(kāi)發(fā)入門(mén)教程
- Python進(jìn)階編程:編寫(xiě)更高效、優(yōu)雅的Python代碼
- Java虛擬機(jī)字節(jié)碼:從入門(mén)到實(shí)戰(zhàn)
- Banana Pi Cookbook
- Nexus規(guī)模化Scrum框架
- Elasticsearch for Hadoop
- 常用工具軟件立體化教程(微課版)
- 微服務(wù)從小白到專家:Spring Cloud和Kubernetes實(shí)戰(zhàn)
- 動(dòng)手學(xué)數(shù)據(jù)結(jié)構(gòu)與算法