Now that we know how to express โtrue or falseโ questions in Python, itโs time to put them to use in programs. Weโll take different actions depending on whether a condition is true or false with conditional statements.
The first line is the header line. The boolean expression after the if keyword is called the condition. We end the header line with a colon character (:), and the line(s) after the if statement are indented.
If the logical condition is true, then the indented statement gets executed. If the logical condition is false, the indented statement is skipped. The flowchart is shown in Figureย 2.3.1
The general form of an if statement consists of a header line (the word if followed by a condition and ending with a colon character :). The header is followed by an indented block. That block is the body of the if statement. The statement consists of a header line that ends with the colon character (:) followed by an indented block. Statements like this are called compound statements because they stretch across more than one line.
There is no limit on the number of statements that can appear in the body of an if, but there must be at least one. Occasionally, it is useful to have a body with no statements (usually as a place holder for code you havenโt written yet). In that case, you can use the pass statement, which does nothing.
If you enter an if statement in the Python interpreter, the prompt will change from three chevrons to three dots to indicate you are in the middle of a block of statements, as shown below:
if x > 0 or x < 10:
print ("condition true")
print ("All done")
all values of x
This will be true if x is greater than 0 or less than 10. This covers all possible values of x.
1 to 9
Try again. This would be true if the boolean expressions were joined with and instead of or.
0 to 9
Try again. This would be true if the boolean expressions were joined with and instead of or and if the first boolean expression was x >= 0.
1 to 10
Try again. This would be true if the boolean expressions were joined with and instead of or and if the first logical expression was x >= 0 and the second expression was x <= 10.