- The Python Apprentice
- Robert Smallshire Austin Bingham
- 195字
- 2025-04-04 19:04:57
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.