48
Conditionals and Recursion
>>> 17 and True
True
This flexibility can be useful, but there are some subtleties to it that might be
confusing. You might want to avoid it (unless you know what you are doing).
5.4
CONDITIONAL EXECUTION
In order to write useful programs, we almost always need the ability to check condi-
tions and change the behavior of the program accordingly.
Conditional statements
give us this ability. The simplest form is the if statement:
if x > 0:
print 'x is positive'
The boolean expression after the if statement is called the
condition. If it is true,
then the indented statement gets executed. If not, nothing happens.
if
statements have the same structure as function definitions: a header followed by
an indented block. Statements like this are called
compound statements.
There is no limit on the number of statements that can appear in the body, but there
has to be at least one. Occasionally, it is useful to have a body with no statements
(usually as a place keeper for code you haven’t written yet). In that case, you can use
the pass statement, which does nothing.
if x < 0:
pass
# need to handle negative values!
Chia sẻ với bạn bè của bạn: